The switch Statement

There is an alternative to an if statement that you can use in PHP, just as in JavaScript, called a switch case statement. With a switch case statement you take a single variable that you want to compare against a list of possible values.

switch( $age ){ 
  case 20: 
    echo "Twenty"; 
    break; 
  case 25: 
    echo "Twenty-Five"; 
    break; 
  case 30: 
    echo "Thirty"; 
    break; 
  default: 
    echo "Other"; 
}

This statement looks at three possible values for the variable $age. Each possible value is written with the word case in front of it. The word break indicates the end of a section. If the value of the variable $age were 25 then the echo "Twenty-Five"; line would run and the break command would exit from the case statement without checking any of the other possible matches after that line.

If we want to do the same thing based on several possible matches we can just list all the possible matches without breaks before the command(s) we want to run. Here is an example of that:

switch( $age ){ 
  case 10: 
  case 11: 
  case 12: 
    echo "ten, eleven or twelve"; 
    break; 
  case 13: 
  case 14: 
  case 15: 
    echo "thirteen, fourteen, or fifteen"; 
}

TIP

The keyword default: is comparable to the else portion of an if / else statement.