Skip to the workspace
Pebellslearn by building
Conditionals  ›  Lesson

switch

switch 12 minswitch compares one value against a list of cases using loose equality, starts at the first match and keeps running through later cases until it reaches break.

php / switch

Explore each scene at your own pace.

01 · The rule

The rule

switch

switch compares one value against a list of cases using loose equality, starts at the first match and keeps running through later cases until it reaches break.

Inspect comparison and fall-through behavior before using switch for alternatives.

Pageturn sells paperbacks, hardbacks, ebooks and audiobooks, and the delivery cost depends on the format. A long chain of elseif ($format === ...) works, but it repeats $format on every line. switch compares one value against a list of cases instead.

The rule

switch jumps to the matching case and falls through until break.

<?php
$format = "hardback";

switch ($format) {
    case "paperback":
    case "hardback":
        $delivery = 3.50;
        break;
    case "ebook":
    case "audio":
        $delivery = 0;
        break;
    default:
        $delivery = null;   // unknown format
}

The mechanics:

  • switch ($value) evaluates the value once.
  • PHP looks for the first case that equals it and starts running there.
  • It keeps running downward through the following cases until it meets break (or the end). This is called fall-through.
  • default runs when no case matched. It is optional but usually wise.

Fall-through is useful on purpose: stacking case "paperback": and case "hardback": with nothing between them makes both share one block, as above.

It is dangerous by accident. Forget one break and the next case's code runs as well:

switch ("ebook") {
    case "ebook": echo "e";   // no break!
    case "audio": echo "a"; break;
}
// prints: ea

One more detail: switch compares with loose equality (==), so types can be converted. switch ("1") will match case 1:. When exact types matter, the match expression in the next lesson compares strictly.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.