[ Team LiB ] Previous Section Next Section

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".

Listing 5.1 An if Statement
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.1 An if Statement</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $satisfied = "very";
12: if ( $satisfied == "very" ) {
13:   print "We are pleased that you are happy with our service";
14:   // register customer satisfaction in some way
15: }
16: ?>
17: </div>
18: </body>
19: </html>

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";

graphics/bytheway_icon.gif

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".

Listing 5.2 An if Statement That Uses else
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.2 An if Statement That Uses else</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: // $satisfied = "very";
12: if ( $satisfied == "very" ) {
13:   print "We are pleased that you are happy with our service";
14:   // register customer satisfaction in some way
15: } else {
16:   print "Please take a moment to rate our service";
17:   // present pulldown
18: }
19: ?>
20: </div>
21: </body>
22: </html>

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.

graphics/bytheway_icon.gif

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


Listing 5.3 adds an else if clause to the previous example.

Listing 5.3 An if statement That Uses else and else if
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.3 An if statement That Uses else and else if</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $satisfied = "no";
12: if ( $satisfied == "very" ) {
13:   print "We are pleased that you are happy with our service";
14:   // register customer satisfaction in some way
15: } else if ( $satisfied == "no")  {
16:   print "We are sorry that we have not met your expectations";
17:   // request further feedback
18: } else {
19:   print "Please take a moment to rate our service";
20:   // present pulldown
21: }
22: ?>
23: </div>
24: </body>
25: </html>

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:


switch (expression) {
    case result1:
      // execute this if expression results in result1
      break;
    case result2:
      // execute this if expression results in result2
      break;
    default:
      // execute this if no break statement
      // has been encountered hitherto
}

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.

graphics/watchout_icon.gif

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:


switch ( $satisfied ) {
   case "very":
   case "quite":
   case "almost":
     print "We are pleased...";
     break;

   case "disatisfied":
   case "no":
   case "unhappy":
     print "We are sorry...";
     break;
// ...
}

Be aware of your breaks!


Listing 5.4 re-creates the functionality of the if statement example, using the switch statement.

Listing 5.4 A switch Statement
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.4 A switch Statement</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $satisfied = "no";
12: switch ( $satisfied ) {
13:   case "very":
14:     print "We are pleased that you are happy with our service";
15:     break;
16:   case "no":
17:     print "We are sorry that we have not met your expectations";
18:     break;
19:   default:
20:     print "Please take a moment to rate our service";
21: }
22: ?>
23: </div>
24: </body>
25: </html>

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:


(expression) ?returned_if_expression_is_true:returned_if_expression_is_false;

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.

Listing 5.5 Using the ? Operator
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.5 Using the ? Operator</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $satisfied = "no";
12:
13: $pleased = "We are pleased that you are happy with our service";
14: $sorry = "We are sorry that we have not met your expectations";
15:
16: $text = ( $satisfied=="very" )?$pleased:$sorry;
17: print "$text";
18: ?>
19: </div>
20: </body>
21: </html>

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.

    [ Team LiB ] Previous Section Next Section