Page 102 - Open Soource Technologies 304.indd
P. 102
Unit 6: Building Blocks of PHP
... Notes
if ($error_code == MY_ERROR) {
print(“There was an error\n”);
6.1.6 Switch Flow
Statement. Statement List
switch (expr){ switch (expr):
case expr:
case expr:
statement list
statement list case expr:
statement list
default:
statement list
endswitch;
case expr:
statement list
...
default:
statement list
You can use the switch construct to elegantly replace certain lengthy if/elseif constructs. It is given
an expression and compares it to all possible case expressions listed in its body. When there’s
a successful match, the following code is executed, ignoring any further case lines (execution
does not stop when the next case is reached). The match is done internally using the regular
equality operator (==), not the identical operator (===). You can use the break statement to end
execution and skip to the code following the switch construct:
}
Usually, break statements appear at the end of a case statement list, although it is not mandatory.
If no case expression is met and the switch construct contains default, the default statement list
is executed. Note that the default case must appear last in the list of cases or not appear at all:
switch ($answer) {
case ‘y’:
case ‘Y’:
print “The answer was yes\n”;
LOVELY PROFESSIONAL UNIVERSITY 97