The Switch Construct

The switch construct compares the value of a variable with a series of values and executes the corresponding code block. If no values match, default code can be executed. Each code block must end with a break statement to prevent execution of subsequent blocks.

Syntax

phpswitch ($variable) {
  case value1:
    // code to execute
    break;
  case value2:
    // code to execute
    break;
  default:
    // default code
}

Example

A simple example of using switch to determine the day of the week:

php<?php
  $day = 3;
  
  switch ($day) {
    case 1:
      echo 'Monday';
      break;
    case 2:
      echo 'Tuesday';
      break;
    case 3:
      echo 'Wednesday';
      break;
    default:
      echo 'Invalid day';
  }
?>

Code execution result:

php'Wednesday'

Example

Example with multiple case statements for one code block:

php<?php
  $grade = 'B';
  
  switch ($grade) {
    case 'A':
    case 'B':
      echo 'Well done!';
      break;
    case 'C':
      echo 'Good';
      break;
    default:
      echo 'Try again';
  }
?>

Code execution result:

php'Well done!'

See Also

  • the if construct,
    which checks a condition
  • the while construct,
    which creates a loop with a condition