1: <html>
2: <head>
3: <title>Listing 5.3</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: elseif ( $mood == "sad" )
13: {
14: print "Awww. Don't be down!";
15: }
16: else
17: {
18: print "Neither happy nor sad but $mood";
19: }
20: ?>
21: </body>
22: </html>
Once again, $mood holds a string, "sad". This is not equivalent to "happy", so the
first block is ignored. The elseif clause tests for equivalence between the contents of
$mood and "sad", which evaluates to true. This block of code is therefore executed.
The switch Statement
The switch statement is an alternative way of changing program flow according to
the evaluation of an expression. There are some key differences between the switch
and if statements. Using the if statement in conjunction with elseif, you may
evaluate multiple expressions. switch evaluates only one expression, executing
different code according to the result of that expression, as long as the expression
evaluates to a simple type (a number, a string, or a boolean). The result of an
expression evaluated as part of an if statement is read as either true or false. The
expression of a switch statement yields a result that is tested against any number of
values.
switch ( expression )
{
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
The switch statement's expression is often simply a variable. Within the switch
statement's block of code, you find a number of case statements. Each of these
tests a value against the result of the switch statement's expression. If these are
equivalent, then the code after the case statement is executed. The break
statement ends execution of the switch statement altogether. If this is left out, the
next case statement's expression is evaluated. If the optional default statement is
reached, its code is executed.
Caution Don't forget to include a break statement at the end of any code that
will be executed as part of a case statement. Without break, the
program flow will continue to the next case statement and ultimately
to the default statement. In most cases, this will not be the behavior
that you will be expecting.
No comments:
Post a Comment