Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

switch

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.

The shortcut

To predict a switch, find the entry point, then run downward until the first break. Do not stop at the next case label; labels are only entry points, not walls.

Tracing a missing breakStep 1 of 4
  1. The value

    $format = "paperback"; in a switch where the paperback case sets $delivery = 3.50; but has no break.

Drills

Answer fast — trust the rule.

quick drill

In the delivery switch above, what is $delivery for "audio"?

quick drill

What stops execution from continuing into the next case?

quick drill

A switch on "poster" has cases for four book formats and a default. What runs?

quick drill

Which comparison does switch use to match cases?

Remember

  • switch jumps to the matching case and falls through until break.
  • Shortcut: find the entry point, then run down to the first break.
  • Trap: a forgotten break runs the next case too, and switch compares loosely.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe free paperbacks bug

In a delivery-cost switch, paperbacks suddenly ship for free. The paperback case sets 3.50 but has no break, and the next case sets 0. Explain the bug and the fix.