if ($price > 100) echo "This is expensive";
is correct syntax and will print the message only if $price is greater than 100.
When there's more than one statement to execute, you must surround them with braces:
if ($price > 100) {
echo "This is expensive";
echo "Another time";
}
You can make a construct with if () { } else { }, such that if the first condition is not met
(evaluates to FALSE), the statements contained within the braces of the else { } clause will be
executed. (Note that the braces can be omitted if there is only one statement to execute.)
The most complex form of if is to use if () { } elseif () { } else { }. There can be any
number of elseif () conditions. If the first if () condition is not met, it will try to match the elseif
(), and the next, and so on until the last elseif ().
When one of the conditions is met (evaluates to TRUE), it will execute the given statements and then
finish. If none of the conditions is met, it will execute the else statements. If there is no else, it will
finish without doing anything.
Control Structures: while
PHP offers a simple loop structure in the form of while. A while loop takes the following basic form:
while (expression) {
# do some statements;
}
Upon entering the loop, the expression is evaluated and, if it is TRUE, execution proceeds to the
statements within the loop. Braces around the statements are only required when there is more than
one statement.
while is actually quite similar to if without the elseif and else options. Like if, it only executes the
statements if the expression evaluates to TRUE, but, having done the statements once, while will go
back to the beginning and evaluate expression again, and keep doing so until it evaluates to FALSE,
whereupon it will finish the loop and continue with the rest of the code.
Consider a simple example of HTML and PHP for counting down from 3 to 0:
Countdown with while<br>
<?php
$n = 4;
while (--$n)
echo "$n...";
?>
which will produce
Countdown with while
3...2...1...
What happens here? Each time execution enters the while loop, the $n variable decrements by one
and is then evaluated as TRUE or FALSE. The first time into the loop, it evaluates to 3, which is TRUE as
far as the while logic is concerned, so it executes the echo statement.
The fourth time through into the loop, $n is 1 and decrementing again makes it zero. This means
FALSE, and execution therefore skips the echo statement and finishes.
A second form of the while loop is do...while. This takes the following form:
do {
# some statements
} while (expression)
Unlike the first form of while, this form guarantees that the statements within the braces will be
executed at least once. The expression will not be evaluated until the end of the loop; if TRUE at that
point, the loop will be repeated. The looping will continue until expression evaluates to FALSE.