Page 63 - Open Soource Technologies 304.indd
P. 63
Unit 3: Flow-Control Statements and PHP in Web Page
The break statement can also be used in an odd way in PHP that can cause errors if you are not Notes
aware of it. If the break statements are the only statement following a given case statement, the
code will skip to the default statement block instead of the end of the switch statement.
This may seem a little odd for experienced programmers because it raises the question—why
include a separate case statement for something that should fall into the default? The primary
reason is that it allows you to exclude certain values that might otherwise meet a later condition.
For instance, if we go back to our example and wanted to code to run the default statements for
a number between zero and nine or for any number divisible by 10, we could code:
switch ($xyz) {
case is_int($xyz) == false:
echo ($xyz . ‘ is not an integer!’);
break
case $xyz <= 0:
echo ($xyz . ‘ is too low!’);
break
// the following statement will skip to
// the default
case $xyz % 10 == 0:
break;
case $xyz >= 10:
echo ($xyz .+ ‘ is too high!’);
break
default:
echo ($ xyz . ‘ is within acceptable limits!’);
$abc = someFunc($xyz);
break;
}
If you forget the break statement, then the code will fall through, which is to
say that the code will start executing at the label that matches the value of the
expression being evaluated, and then will proceed to process all codes until
either the end of the switch statement or until it find a break statement.
3.1.3 Other Formats
PHP likes to cover its bases, so it provides alternate methods for coding if statements and switch
statements.
Alternate If
There are two alternate ways to code an if statement, one is a ternary operator, and another one
is an alternate syntax.
The ternary operator takes the form of:
(condition) ? value_if_true : value_if_false;
LOVELY PROFESSIONAL UNIVERSITY 57