Page 91 - Beginning PHP 5.3
P. 91
Chapter 4: Decisions and Loops
The first line of the script creates a variable, $widgets , and sets its value to 23 . Then an if statement
uses the == operator to check if the value stored in $widgets does indeed equal 23 . If it does — and it
should! — the expression evaluates to true and the script displays the message: “ We have exactly 23
widgets in stock! ” If $widgets doesn ’ t hold the value 23 , the code between the parentheses — that is,
the echo() statement — is skipped. (You can test this for yourself by changing the value in the first line
of code and re - running the example.)
Here ’ s another example that uses the > (greater than or equal) and < (less than or equal) comparison
=
=
operators, as well as the & & (and) logical operator:
$widgets = 23;
if ( $widgets > = 10 & & $widgets < = 20 ) {
echo “We have between 10 and 20 widgets in stock.”;
}
This example is similar to the previous one, but the test expression inside the parentheses is slightly
more complex. If the value stored in $widgets is greater than or equal to 10 , and it ’ s also less than or
equal to 20 , the expression evaluates to true and the message “ We have between 10 and 20 widgets in
stock. ” is displayed. If either of the comparison operations evaluates to false , the overall expression
also evaluates to false , the echo() statement is skipped, and nothing is displayed.
The key point to remember is that, no matter how complex your test expression is, if the whole
expression evaluates to true the code inside the braces is run; otherwise the code inside the braces is
skipped and execution continues with the first line of code after the closing brace.
You can have as many lines of code between the braces as you like, and the code can do anything, such
as display something in the browser, call a function, or even exit the script. In fact, here ’ s the previous
example rewritten to use an if statement inside another if statement:
$widgets = 23;
if ( $widgets > = 10 ) {
if ( $widgets < = 20 ) {
echo “We have between 10 and 20 widgets in stock.”;
}
}
The code block between the braces of the first if statement is itself another if statement. The first if
statement runs its code block if $widgets > = 10 , whereas the inner if statement runs its code block —
the echo() statement — if $widgets < = 20 . Because both if expressions need to evaluate to true for
the echo() statement to run, the end result is the same as the previous example.
If you only have one line of code between the braces you can, in fact, omit the braces altogether:
$widgets = 23;
if ( $widgets == 23 )
echo “We have exactly 23 widgets in stock!”;
However, if you do this, take care to add braces if you later add additional lines of code to the code
block. Otherwise, your code will not run as expected!
53
9/21/09 8:52:06 AM
c04.indd 53
c04.indd 53 9/21/09 8:52:06 AM