The PHP Scripting Language - switch Statement (
Page 5 of 10 )
The switch statement can be used as an alternative to if to select an option from a list of choices. The following example executes different code for different integer values, or cases of the variable $menu
. A
case
clause is provided for values 1, 2, 3, and 4, with a
default
: case provided for all other values:
switch ($menu)
{
case 1:
print "You picked one";
break;
case 2:
print "You picked two";
break;
case 3:
print "You picked three";
break;
case 4:
print "You picked four";
break;
default:
print "You picked another option";
}
This example can be implemented with
if
and
elseif
, but the
switch
method is usu
ally more compact, readable, and easier to type. The use of
break
statements is important: they prevent execution of statements that follow in the
switch
statement and force execution to jump to the statement that follows the closing brace.
If
break
statements are omitted from a
switch
statement, you can get an unexpected result. For example, without the
break
statements, if the user chooses option 3, the script outputs:
You picked three. You picked four. You picked another option
These results are often a source of difficult-to-detect bugs; however, by intentionally omitting the
break
statement, you can group cases together as shown in the following
switch
statement:
$score = "Distinction";
switch ($score)
{
case "High Distinction":
case "Distinction":
print "Good student";
break;
case "Credit":
case "Pass":
print "Average student";
break;
default:
print "Poor student";
}
While not mandatory, the
default
: case is useful when default processing is performed on all but selected special cases, or to handle unexpected values when expected values have corresponding cases.
Conditional Expressions
Now we’ll look at what can go inside the parentheses of an if statement, and other control statements. The most common conditional comparison is to test the equality or inequality of two expressions. Equality is checked with the double-equal operator, == ; if the value on the left-hand side is equal to the value on the right-hand side, then the expression evaluates to true
. The expression
($var == 3)
in the following example evaluates to true:
$var = 3;
if ($var == 3)
print "Equals 3";
Inequality is tested with the not-equals operator,
!=
. Both evaluate to a Boolean result of
true
or
false
.
If the equality operator == and the assignment operator = are unfamiliar, beware: they are easy to inadvertently interchange. This is a very common bug and hard to detect.
The value of the conditional expression (
$var = 1
) evaluates as true, because the expression takes its value from the value on the right hand side of the assignment operator; in this case 1. Here is an example of a common mistake, which overwrites the original value of the variable and always prints the statement:
if ($var = 1
)
print"Variable equals 1.";
The error of incorrectly replacing an assignment with == is a far less common mistake. However, it’s also difficult to detect because an incorrectly written assignment of
$var == 1;
is quietly evaluated as true or false with no effect on
$var
.
Expressions can be combined with parentheses and with the Boolean operators
&&
(and) and
||
(or). For example, the following expression returns true and prints the message if $var is equal to 3 or $var2 is equal to 7:
if (($var == 3) || ($var2 == 7))
print "Equals 3 or 7";
The following expression returns
true
and prints the message if
$var
equals 2 and
$var2
equals 6:
if (($var == 2) && ($var2 == 6))
print "The variables are equal to 2 and 6";
Interestingly, if the first part of the expression
($var == 2)
evaluates as
false
, PHP doesn’t evaluate the second part of the expression
($var2 == 6)
, because the overall expression can never be
true
; both conditions must be
true
for an
&&
(and) opera
tion to be
true
. Similarly, in the previous example, if
($var == 3)
, then there’s no need to check if
($var2 == 7)
.
This short-circuit evaluation property has implications for design; to speed code, write the expression most likely to evaluate as
false
as the left-most expression, and ensure that computationally expensive operations are as right-most as possible.
Never assume that expressions combined with the Boolean operators
&&
and
||
are evaluated. PHP uses short-circuit evaluation when determining the result of a Boolean expression.
Conditional expressions can be negated with the Boolean not operator !. The following example shows how an expression that tests if
$var
is equal to 2 or 6 is negated:
if (($var == 2) || ($var == 6)
)
print "The variable var is equal to 2 or 6";
if (!(($var == 2) || ($var == 6)))
print "The variable var is not equal to 2 or 6";
Unlike the
&&
and
||
operators,
!
works on a single value as the following example highlights:
// Set a Boolean variable
$found = false;
// The following message is printed
if (!$found)
print "Expression is true";
More complex expressions can be formed through combinations of the Boolean operators and the liberal use of parentheses. For example, the following expression evaluates as
true
and prints the message if one of the following is
true: $var
equals 6 and
$var2
equals 7, or
$var
equals 4 and
$var2
equals 1.
if ((($var == 6) && ($var2 == 7)) || (($var == 4) && ($var2 == 1)))
print "Expression is true";
As in assignment expressions, parentheses ensure that evaluation occurs in the required order.
Loops
Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while
,
for
, and
foreach
. The first three are general-purpose loop constructs, while the foreach is used exclusively with arrays and is discussed in the next chapter.
while
The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements—the loop body—as long as a condition remains true. The condition is checked first, then the loop body is exe
cuted. So, the loop never executes if the condition isn’t initially
true
. Just as with the
if
statement, more than one statement can be placed in braces to form the loop body.
The following fragment illustrates the
while
statement by printing out the integers from 1 to 10 separated by a space character:
$counter = 1
;
while ($counter < 11)
{
print $counter . " ";
$counter++;
}
do...while
The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remains
true
, the loop body is repeated.
You can emulate the functionality of the previous
while
example as follows:
$counter = 1;
do
{
print $counter . " ";
$counter++;
} while ($counter < 11);
The contrast between
while
and
do...while
can be seen in the following example:
$counter = 100;
do
{
print $counter . " ";
$counter++;
} while ($counter < 11);
This example outputs 100, because the body of the loop is executed once before the condition is evaluated as
false
.
The
do...while
loop is the least frequently used loop construct, probably because executing a loop body once when a condition is
false
is an unusual requirement.
for
The for loop is the most complicated of the loop constructs, but it also leads to the most compact code.
Consider this fragment that implements the example used to illustrate
while
and
do...while
:
for($counter=1; $counter<11; $counter++)
{
print $counter;
print " ";
}
The
for
loop statement has three parts separated by semicolons, and all parts are optional:
Initial statements
Statements that are executed once, before the loop body is executed.
Loop conditions
The conditional expression that is evaluated before each execution of the loop body. If the conditional expression evaluates as false, the loop body is not exe
cuted.
End-loop statements
Statements that are executed each time after the loop body is executed.
The previous code fragment has the same output as our
while
and
do...while
loop count-to-10 examples.
$counter=1
is an initial statement that is executed only once, before the loop body is executed. The loop condition is
$counter<11
, and this is checked each time before the loop body is executed; when the condition is no longer
true
(when
$counter
reaches 11) the loop is terminated. The end-loop statement
$counter++
is executed each time after the loop body statements.
Our example is a typical
for
loop. The initial statement sets up a counter, the loop condition checks the counter, and the end-loop statement increments the counter. Most
for
loops used in PHP scripts have this format.
Conditions can be as complex as required, as in an
if
statement. Moreover, several initial and end-loop statements can be separated by commas. This allows for complexity:
for($x=0,$y=0; $x<10&&$y<$z; $x++,$y+=2)
However, complex
for
loops can lead to confusing code.