[Previous] [Contents] [Next]

switch Statement

The switch statement can be used as an alternative to if to select an option from a list of choices:

  $menu = 3;
  
switch ($menu)
{
  case 1:
    echo "You picked one";
    break;
  case 2:
    echo "You picked two";
    break;
  case 3:
    echo "You picked three";
    break;
  case 4:
    echo "You picked four";
    break;
  default:
    echo "You picked another option";
}

This example can be implemented with if and elseif, but the switch method is usually more compact, readable, and efficient to type. The use of break statements is important: they prevent execution of statements that follow in the switch statement and continue execution with the statement that follows the closing brace.

If break statements are omitted from a switch statement, you get a bug. If the user chooses option 3, the script outputs not just:

 "You picked three"

but also:

"You picked three. You picked four. You picked another option"

The fact that break statements are needed is sometimes considered to be a feature but is more often a source of difficult-to-detect bugs.

Using if and elseif

  $menu = 3;
  if ($menu == 1) {
    echo "You picked one";
  }
  elseif ($menu == 2) {
    echo "You picked two";
  }
  elseif ($menu == 3) {
    echo "You picked three";
  }
  elseif ($menu == 4){
    echo "You picked four";
  }
  else {
    echo "You picked another option";
  }

The above two examples are two different ways to write the same thing, one using if and elseif statements, and the other using the switch statement.

[Previous] [Contents] [Next]