PHP ยท Chapter 14 of 44

PHP Switch Statement

The switch statement is used to perform different actions based on different possible values of a single variable, avoiding long chains of elseif statements. Each possible value is a case.

Each case should typically end with a break statement to prevent execution from falling through to the next case. A default case can be included to run when no other case matches.

Syntax
switch ($var) {
  case value1:
    // code
    break;
  default:
    // code
}

How switch works

PHP compares the switch expression against each case value using loose comparison. When a match is found, PHP runs the code for that case until it hits a break or the end of the switch block.

The default case

default runs when none of the case values match the expression, similar to a final else in an if/elseif chain.

Example 1 (php)
<?php
  $day = "Mon";
  switch ($day) {
    case "Mon":
      echo "Monday";
      break;
    default:
      echo "Another day";
  }
?>
Output
Monday

Since $day matches "Mon", that case runs and break stops further checks.

Example 2 (php)
<?php
  $grade = "F";
  switch ($grade) {
    case "A":
    case "B":
      echo "Good job";
      break;
    default:
      echo "Keep trying";
  }
?>
Output
Keep trying

Since $grade doesn't match A or B, execution falls to the default case.

Key points

  • switch compares one expression against multiple case values.
  • break prevents falling through to the next case.
  • default runs when no case matches.
  • Multiple case labels can share the same block of code.
๐Ÿ’ก Note: Forgetting break is a very common bug โ€” it causes execution to 'fall through' into the next case unintentionally.

๐Ÿ“ Quick Quiz

1. What keyword stops fall-through in a switch case?

2. What runs when no case matches?

3. Can multiple case labels share the same code block?