Conditionals add control to scripts and permit choices. Different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optional else clause, and switch, usually with two or more case clauses.
The if statement conditionally controls execution. The basic format of an if statement is to test whether a condition is true and, if so, to execute one or more statements.
The following if statement executes the print statement and outputs the string when the conditional expression, $var is greater than 5, is true:
if ($var > 5) print "The variable is greater than 5";
|
Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates as true, the statements within the braces are executed. If the expression isn't true, none of the statements are executed. Consider an example in which three statements are executed if the condition is true:
if ($var > 5) { print "The variable is greater than 5."; // So, now let's set it to 5 $var = 5; print "In fact, now it is equal to 5."; }
Without the braces, an if statement executes only the single, immediately following statement when the conditional expression evaluates to true.
The if statement can have an optional else clause to execute a statement or block of statements if the expression evaluates as false. Consider an example:
if ($var > 5) print "Variable greater than 5"; else print "Variable less than or equal to 5";
It's also common for the else clause to execute a block of statements in braces, as in this example:
if ($var < 5) { print "Variable is less than 5"; print "-----------------------"; } else { print "Variable is equal to or larger than 5"; print "-------------------------------------"; }
Consecutive conditional tests can lead to examples such as:
if ($var < 5) print "Value is very small"; else if ($var < 10) print "Value is small"; else if ($var < 20) print "Value is normal"; else if ($var < 30) print "Value is big"; else print "Value is very big";
The indentation in the preceding example highlights the nested nature of the multiple tests. If consecutive, cascading tests are needed, the elseif statement can be used. The choice of which method to use is a matter of personal preference. This example has the same functionality as the previous example:
if ($var < 5) print "Value is very small"; elseif ($var < 10) print "Value is small"; elseif ($var < 20) print "Value is normal"; elseif ($var < 30) print "Value is big"; else print "Value is very big";
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 usually 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.
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.
|
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) operation 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.
|
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.