PHP logic statements
PHP scripts are a series of statements. These can include assignment statements, function calls and logical statements such as if, for loops, while loops. Multiple statements can be grouped within braces ( { ... } ).
if (condition) statement;
if (condition)
statement
else
statement;
if (condition)
statement
elseif (condition)
statement
else
statement;
Example:
$a = 5;
$b = 10;
if ($a == $b) {
print "$a == $b"
} elseif ($a > $b) {
print "$a > $b"
} else {
print "$a < $b"}
Yields the following:
5 < 10
While loops are the most general type of loop. PHP's While syntax is:
while (condition) statement;
For example:
$i = 1;
while ($i <= 10) {
print "$i ";
$i++;
}
Yields:
1 2 3 4 5 6 7 8 9 10
For loops are another powerful and common construct. Syntax:
for(expr1; expr2; expr3) {
}
expr1 is executed at the beginning of the loop, expr2 is evaluated at the beginning of each iteration and if TRUE the loop continues, expr3 is executed at the end of each iteration. The expressions can actually be multiple statements separated by ,'s. Example:
for ($i=1; $i <= 10; $i++) {
print "$i ";
}
Yields:
1 2 3 4 5 6 7 8 9 10
Alternative
for ($i = 1; $i <= 10; print "$i ", $i++) ;
1 2 3 4 5 6 7 8 9 10
Page Source
<< Syntax | PHP Tour | >> Functions