[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:

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.


[Previous] [Contents] [Next]