Switching Flow

Most scripts evaluate conditions and change their behavior accordingly. This facility to make decisions makes your PHP pages dynamic, capable of changing their output according to circumstances. In common with most programming languages, PHP enables you to do this with an if statement.

The if Statement

An if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block of code inside braces). The if statement evaluates an expression between parentheses. If this expression results in a true value, the statement is executed. Otherwise, the statement is skipped entirely. This enables scripts to make decisions based on any number of factors.

In the following fragment, we show the structure of an if statement. The test expression is represented by the string 'expression':

if (expression) {
// code to execute if the expression evaluates to true
}

Listing 5.1 executes a block of code only if a variable contains the string "very".

You use the comparison operator (==) to compare the variable $satisfied with the string "very". If they match, the expression evaluates to true and the code block below the if statement is executed. Although the code block is wrapped in braces in the example, this is only necessary if the block contains more than one line. The following fragment, therefore, would be acceptable:

if ( $satisfied == "very")
print "We are pleased that you are happy with our service";

Style guides often discourage the omission of braces from single-line code blocks. Using braces, it is argued, promotes readability and guards against errors that might occur when adding new lines to previously single-line code blocks.

If you change the value of $satisfied to "no" and run the script, the expression in the if statement evaluates to false and the code block is skipped. The script remains sulkily silent.

Using the else Clause with the if Statement

When working with the if statement, you will often want to define an alternative block of code that should be executed if the expression you are testing evaluates to false. You can do this by adding else to the if statement followed by a further block of code, like so:

if (expression) {
// code to execute if the expression evaluates to true
} else {
// code to execute in all other cases
}

Listing 5.2 amends the example in Listing 5.1 so that a default block of code is executed if $satisfied is not equivalent to "very".

Notice that the assignment to the $satisfied variable on line 11 has been commented out, so the expression in the if statement in line 12 evaluates to false. This means the first block of code (line 13) is skipped. The block of code after else, therefore, is executed and the message "Please take a moment to rate our service" is printed to the browser.

Using the else clause with the if statement enables scripts to make sophisticated decisions, but you currently are limited to an either-or branch. PHP allows you to evaluate multiple expressions one after the other.

Using the else if Clause with the if Statement

You can use an if/else else/if construct to test multiple expressions before offering a default block of code:

if ( expression ) {
// code to execute if the expression evaluates to true
} else if ( another expression ) {
// code to execute if the previous expression failed
// and this one evaluates to true
} else {
// code to execute in all other cases
}

If the first expression does not evaluate to true, the first block of code is ignored. The else if clause then causes another expression to be evaluated. Once again, if this expression evaluates to true, the second block of code is executed. Otherwise, the block of code associated with the else clause is executed. You can include as many else if clauses as you want, and if you don't need a default action, you can omit the else clause.

The else if clause can also be written as a single word: elseif. The syntax you employ is a matter of taste.

Once again, $satisfied holds a string ("no") in line 11. This is not equivalent to "very", so the first block in line 13 is ignored. The else if clause in line 15 tests for equivalence between the contents of $satisfied and "no", which evaluates to true. This block of code is therefore executed. From line 18, we provide default behavior. If none of the test conditions have been fulfilled, we simply print a message requesting input.

The switch Statement

The switch statement is an alternative way of changing program flow according to the evaluation of an expression. Some key differences exist between the switch and if statements. Using the if statement in conjunction with else if, you can evaluate multiple expressions. switch evaluates only one expression, executing different code according to the result of that expression, as long as the expression evaluates to a simple type (a number, string, or Boolean). The result of an expression evaluated as part of an if statement is read as either true or false, whereas the expression of a switch statement yields a result that is tested against any number of values, as shown here:

The switch statement's expression is often simply a variable. Within the switch statement's block of code, you find a number of case statements. Each of these tests a value against the result of the switch statement's expression. If these are equivalent, the code after the case statement is executed. The break statement ends execution of the switch statement altogether. If this is omitted, the next case statement's expression is evaluated. If the optional default statement is reached, its code is executed.

In most circumstances, don't forget to include a break statement at the end of any code that will be executed as part of a case statement. Without break, the program flow continues to the next case statement and ultimately to the default statement. In most cases, this is not the behavior you expect.

Having said that, this feature can also be used to your advantage. In particular, you might want to omit a break for a case statement so that multiple tests can result in a single action. In the following fragment, we group case conditions together in this way:

In line 11 the $satisfied variable is initialized to "no", and the switch statement in line 12 uses this variable as its expression. The first case statement in line 13 tests for equivalence between "very" and the value of $satisfied. There is no match, so script execution moves on to the second case statement in line 16. The string "no" is equivalent to the value of $satisfied, so this block of code is executed. The break statement in line 18 ends the process.

Using the ? Operator

The ?, or ternary, operator is similar to the if statement but returns a value derived from one of two expressions separated by a colon. Which expression is used to generate the value returned depends on the result of a test expression:

If the test expression evaluates to true, the result of the second expression is returned; otherwise, the value of the third expression is returned. Listing 5.5 uses the ternary operator to set the value of a variable according to the value of $satisfied.

In line 11, $satisfied is set to "no". Then, in line 16, $satisfied is tested for equivalence to the string "very". Because this test returns false, the result of the third of the three expressions is returned. Note that variables are used on lines 13 and 14 to store the alternative output strings. This makes the code more readable than it would be with the strings embedded in the ternary statement.

The ternary operator can be difficult to read but is useful if you are dealing with only two alternatives and like to write compact code.