Page 92 - Beginning PHP 5.3
P. 92
Part II: Learning the Language
Providing an Alternative Choice with the else Statement
As you ’ ve seen, the if statement allows you to run a block of code if an expression evaluates to true . If
the expression evaluates to false , the code is skipped.
You can enhance this decision - making process by adding an else statement to an if construction. This
lets you run one block of code if an expression is true , and a different block of code if the expression is
false . For example:
if ( $widgets > = 10 ) {
echo “We have plenty of widgets in stock.”;
} else {
echo “Less than 10 widgets left. Time to order some more!”;
}
If $widgets is greater than or equal to 10 , the first code block is run, and the message “ We have plenty
of widgets in stock. ” is displayed. However, if $widgets is less than 10 , the second code block is run,
and the visitor sees the message: “ Less than 10 widgets left. Time to order some more! ”
You can even combine the else statement with another if statement to make as many alternative
choices as you like:
if ( $widgets > = 10 ) {
echo “We have plenty of widgets in stock.”;
} else if ( $widgets > = 5 ) {
echo “Less than 10 widgets left. Time to order some more!”;
} else {
echo “Panic stations: Less than 5 widgets left! Order more now!”;
}
If there are 10 or more widgets in stock, the first code block is run, displaying the message: “ We have
plenty of widgets in stock. ” However, if $widgets is less than 10 , control passes to the first else
statement, which in turn runs the second if statement: if ( $widgets > = 5 ) . If this is true the
second message — “ Less than 10 widgets left. Time to order some more! ” — is displayed. However, if
the result of this second if expression is false , execution passes to the final else code block, and the
message “ Panic stations: Less than 5 widgets left! Order more now! ” is displayed.
PHP even gives you a special statement — elseif — that you can use to combine an else and an if
statement. So the preceding example can be rewritten as follows:
if ( $widgets > = 10 ) {
echo “We have plenty of widgets in stock.”;
} elseif ( $widgets > = 5 ) {
echo “Less than 10 widgets left. Time to order some more!”;
} else {
echo “Panic stations: Less than 5 widgets left! Order more now!”;
}
54
9/21/09 8:52:07 AM
c04.indd 54 9/21/09 8:52:07 AM
c04.indd 54