ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations

Control Structures Revisited

08/23/2001

Today we'll revisit our discussion of control structures with the introduction of three new ones: do...while(), if....elseif, and the switch statement.

Last time we discussed control structures we introduced the standard if() statement, the while() statement as well as the for() statement. Today we'll introduce two new variations of these control structures as well as introduce a completely new structure switch() and explain the similarities between it and the other structures.

The 'if' statement revisited

The if statement was the first, and most important, control structure we learned. We learned how to use it to create conditional-executing code and how we could use its companion, the else statement, to guarantee that one part or the other would always be executed. Today we'll introduce briefly a new type of if structure used when multiple conditional checks are needed as well as a rather strange-looking conditional structure called the "conditional assignment" operator.

Let's take a look at an example:

<?php
  $foo = 10;
  $bar = 12;
  if($foo > $bar) {
    echo "$foo is greater than $bar";
  } else {
    if($foo == $bar) {
    echo "$foo is equal to $bar";
    } else {
    echo "$foo is less than $bar";
    }
  }
?>

By now I would hope that the above code is easy to understand. Basically all we are doing is showing the relationship between two integers $foo and $bar and outputting that

Related Reading

PHP Pocket ReferencePHP Pocket Reference
By Rasmus Lerdorf
Table of Contents
Sample Section
Full Description
Read Online -- Safari

relationship to the browser. Although effective, the above set of control structures is very messy and could easily become a nightmare. It is for this reason that PHP has provided us with a different type of else statement called elseif. Its use is identical to a normal if statement except instead of using the else statement we substitute the elseif statement and provide another conditional. The formal syntax for the statement is as follows:

If(<conditon>) {
  ...
} [else[if(<condition>)] {
  ...
} [else {
  ...
} ] ]

When used in practice its primary purpose is to clean up our scripts and make them easier to understand rather than providing any real extra benefits. For an example, we'll rewrite our relationship example to use the new elseif statement:

<?php
  $foo = 10;
  $bar = 12;
  if($foo > $bar) {
    echo "$foo is greater than $bar";
  } elseif($foo == $bar) {
    echo "$foo is equal to $bar";
  } else {
    echo "$foo is less than $bar";
  }
?>

This script will function identically to our original version with the added bonus of removing the need to embed a second if statement within the else of another. There is no limit to how many elseif statements can be "chained" together within a single if conditional statement but any more than two and it is recommended that the switch() statement (that we'll cover later in today's article) be used.

The conditional assignment operator

Consider the following conditional if statement:

<?php
  $foo = 5;
  $bar = 10;
  if($foo > $bar) {
   $foobar = true;
  } else {
   $foobar = false;
  }
?>

Often times it is necessary for a developer to assign the value of a variable depending on the evaluation of a conditional between two others. In this case, we are assigning a boolean value of true or false to the variable $foobar, depending of course on the outcome of the conditional $foo > $bar. As with our first example during our discussion of the elseif statement, the above will work as expected but is rather sloppy.

Today we'll introduce a new type of syntax available in PHP that acts both as a conditional control structure and as an operator all at the same time. This control structure is called (for obvious reasons) the conditional assignment operator. The syntax for this new operator/control structure is as follows:

$var = (<condition>) ? <true value> : <false value>;

Although it looks somewhat strange, it functions exactly as the example just provided. The variable $var is assigned a value dependent on the conditions. If the conditions are "true," the true value will be assigned to $var and conversely if "false," the false value will be assigned. For a better illustration of this, we'll rewrite our example to use this new syntax:

<?php
  $foo = 5;
  $bar = 10;
  $foobar = ($foo > $bar) ? true : false;
?>

As we stated, the above example functions exactly as our previous one and will produce the same result. It is strongly recommended that a conditional assignment operator is used instead of an if statement when attempting to assign a variable either one variable or another. However, for the sake of readability this operator should not be used in the following manner:

<?php
  $foo = 5;
  $bar = 10;
  $boolean = false;
  $foobar = ($foo > $bar) ? 
    	    ($boolean) ? true : false : false;
?>

Where $foobar will only be assigned "true" if $foo is greater than $bar, and $boolean has a value of "true." A better way to write such a conditonal would be:

<?php $foobar = (($foo > $bar) && $boolean) ? true : false; ?>

Or use the standard if conditional structure.

A new look at the 'while' statement

Now that we have covered both elseif and the conditonal assignment operator, we'll quickly take a look at a different flavor of the while statement: the do...while(). The do...while statement is nearly identical in syntax and behavior to a standard while statement with to differences. The first difference is in its syntax, the second is its functionality. The syntax for a do...while statement is:

do {
  ...
} while(<condition);

The real use (and difference) in a do...while statement as opposed to a standard while statement is how many times the code contained within it is guaranteed to execute. In a standard while statement, in theory the code contained within it could never be executed (the conditions required was never achieved). In a do while, the code contained within it will execute at least once (or more depending again on the conditions of the while). Below is an example of using a do...while statement to generate a random number greater than 100:

<?php
  do {
    $myval = rand()
    } while($myval < 100);
?>

The result will be a value $myval that will always be above 100.

The 'switch' control structure

To wrap up our continued discussion of control structures, we'll introduce a very useful alternative to use the if statement: the switch statement. switch statements are unique to any other control structure we have seen thus far, but in essence provide the same functionality as a conditional if statement. For example: Let's assume you would like to develop a script that would process commands from a menu. For argument's sake we'll assume the following menu items:

Home
Links
E-mail Us

In order to make development easier, we'll also assign special one-word identification codes to each of the three menu items. We'll call these home, links, and email respectively.

Now that we have our menu options, and the identification codes assigned to each of them, it is time to write the logic that will determine which option the user selected. When the user clicks on one of our options, we'll send to PHP a variable $menu containing the identification string. So, all we have to do now is check the value of $menu to determine what option the user clicked on. There are a few methods a developer can use to accomplish such a task, such as the use of if...elseif, in code such a method would resemble the following:

<?php
  if($menu == "home") {
    echo "You clicked home";

  } elseif($menu == "links") {

    echo "You clicked links";
  } elseif($menu == "email") {
    echo "You clicked e-mail";
  } else {
    echo "I don't know what you clicked";
  }
?>

Unfortunately, code such as this tends to get confusing and out of hand rather quickly. It is for circumstances such as this that the switch statement was developed.

How the 'switch' statement works

The switch statement could be visually represented as a dial with a number of positions on it. These positions are called "cases." When this imaginary dial is "switched" to one of the positions, a particular piece of code is executed that is associated with that dial. With that in mind, let's examine the syntax of a switch statement:

Switch(<variable>) {
  [case <constant value>:]
  [case <constant value>:]
  ...
  [default:]
}

Looking at the above switch syntax we can see that the statement itself is variable and then within the code block is contained any number of case statements (each requiring a constant value) followed by an optional default case. So how does it work? When a switch statement is executed, it takes the variable passed to it (such as our $menu) and the compares it against each of the case statement values.

In the event that the case statement value matches the value of the variable, the code below the case statement is executed. Optionally, you can also provide a default case to be executed in the event that none of the defined cases matches the provided variable. But, before we can continue and look at it in action we need to introduce a special companion statement to the switch control structure: the break statement.

Using the 'break' statement

When a switch statement matches a particular case, as we stated before, the code directly below it is executed. However, PHP will not stop executing code inside of a switch when it encounters another case statement. Rather, it will ignore all further case statements and execute all of the code below the original match. For example:

<?php
  $menu = "links";
  switch($home) {
    case "home":
      echo "You clicked home";
    case "links":
      echo "You clicked links";
    case "email":
      echo "You clicked e-mail";
    default:
      echo "I don't know what you clicked";
  }
?>

When the above code is executed, instead of the output simply being:

You clicked links

It will output:

You clicked links
You clicked e-mail
I don't know what you clicked

Although the break statement is most commonly found within a switch statement, it can be used in any code block to cancel execution of any further code within that block. Therefore it can be used to escape out of for loops, while loops, or even if statements.

Because PHP was not told to stop executing the code, it continued straight through the entire switch statement and disregarded all further cases. Also note that PHP did not execute the "home" case since it was before the matching case "links." Sometimes, such behavior is beneficial, but in a scenario such as ours we would like to know exactly which case was selected and what menu option was clicked. By using the break statement we can command PHP to stop executing the code and leave the command block as demonstrated below:

<?php
  $menu = "links";
  switch($home) {
    case "home":
      echo "You clicked home";
      break;
    case "links":
      echo "You clicked links";
      break;
    case "email":
      echo "You clicked e-mail";
      break;
   default:
      echo "I don't know what you clicked";
      break;
  }
?>

With the use of the break statement, PHP will only execute the code between the different cases and our output will be as expected.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.