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. Acaseclause is provided for values 1, 2, 3, and 4, with adefault: case provided for all other values:
This example can be implemented withifandelseif, but theswitch method is usually more compact, readable, and easier to type. The use ofbreakstatements is important: they prevent execution of statements that follow in theswitch statement and force execution to jump to the statement that follows the closing brace.
Ifbreakstatements are omitted from aswitchstatement, you can get an unexpected result. For example, without thebreakstatements, 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 thebreakstatement, you can group cases together as shown in the followingswitchstatement:
$score = "Distinction";
While not mandatory, thedefault: 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;
Inequality is tested with the not-equals operator,!=. Both evaluate to a Boolean result oftrueorfalse.
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))
The following expression returnstrueand prints the message if$varequals 2 and$var2equals 6:
if (($var == 2) && ($var2 == 6))
Interestingly, if the first part of the expression($var == 2)evaluates asfalse, PHP doesn’t evaluate the second part of the expression($var2 == 6), because the overall expression can never betrue; both conditions must betruefor an&&(and) operation to betrue. 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 asfalseas the left-most expression, and ensure that computationally expensive operations are as right-most as possible.
Conditional expressions can be negated with the Boolean not operator !. The following example shows how an expression that tests if$varis equal to 2 or 6 is negated:
if (($var == 2) || ($var == 6))
Unlike the&&and||operators,!works on a single value as the following example highlights:
// Set a Boolean variable
More complex expressions can be formed through combinations of the Boolean operators and the liberal use of parentheses. For example, the following expression evaluates astrueand prints the message if one of the following istrue: $varequals 6 and$var2equals 7, or$varequals 4 and$var2equals 1.
if ((($var == 6) && ($var2 == 7)) || (($var == 4) && ($var2 == 1)))
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, andforeach. The first three are general-purpose loop constructs, while the foreach is used exclusively with arrays and is discussed in the next chapter.
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 executed. So, the loop never executes if the condition isn’t initiallytrue. Just as with theifstatement, more than one statement can be placed in braces to form the loop body.
The following fragment illustrates thewhile statement by printing out the integers from 1 to 10 separated by a space character:
$counter = 1;
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 remainstrue, the loop body is repeated.
You can emulate the functionality of the previouswhileexample as follows:
$counter = 1;
The contrast betweenwhileanddo...whilecan be seen in the following example:
$counter = 100;
This example outputs 100, because the body of the loop is executed once before the condition is evaluated asfalse.
Thedo...whileloop is the least frequently used loop construct, probably because executing a loop body once when a condition isfalseis an unusual requirement.
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 illustratewhileanddo...while:
for($counter=1; $counter<11; $counter++)
Theforloop statement has three parts separated by semicolons, and all parts are optional:
Statements that are executed once, before the loop body is executed.
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 executed.
Statements that are executed each time after the loop body is executed.
The previous code fragment has the same output as ourwhile anddo...whileloop count-to-10 examples.$counter=1is 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 longertrue(when$counterreaches 11) the loop is terminated. The end-loop statement$counter++is executed each time after the loop body statements.
Our example is a typicalforloop. The initial statement sets up a counter, the loop condition checks the counter, and the end-loop statement increments the counter. Mostforloops used in PHP scripts have this format.
Conditions can be as complex as required, as in anifstatement. 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, complexforloops can lead to confusing code.
blog comments powered by Disqus