The switch Statement & Fall-Through

The switch Statement & Fall-Through in PHP: --- In the back office of an amusement arcade sits a mechanical coin sorting machine, and it is a good deal…


The Analogy: The Coin Sorting Machine

In the back office of an amusement arcade sits a mechanical coin sorting machine, and it is a good deal cleverer than it looks. You tip a heavy bag of mixed takings into the hopper at the top, and the coins tumble out onto a long rail that slopes gently downward. Cut into that rail is a row of slots, each milled to a precise diameter -- a narrow one first for the smallest coin, then wider and wider slots further down the slope. A coin slides along the rail and is offered to each slot in turn; the first slot it is small enough to drop through swallows it, sending it down a tube into the correct bin below.

The order of those slots is the whole trick. A coin does not survey every slot at once and pick its favourite; it meets them one at a time, from the top of the rail down, and it commits to the very first one that will take it. This is exactly how a switch behaves. The value you hand it is carried past each case in written order, and the first case that equals the value is the one that runs. Nothing below that point is even considered, because by then the coin is already gone down the tube.

Cleverer still, the machine lets several slots empty into one shared chute. All the copper -- pennies and twopences alike -- can be routed to a single cloth bag, because for the purpose of the day's count the office does not care to separate them. Two slots, one destination. That is a group of stacked case labels sharing one body. And right at the bottom of the rail, past the last slot, sits an open reject cup. Any coin that fit no slot at all rolls off the end and lands there, to be examined by hand. That cup is the default: the arm that catches everything the named cases missed.

The failures are where the machine earns its reputation for mischief. Each slot has a small sprung stop meant to catch the coin and settle it in its tube -- that stop is the break. Let one stop wear thin and the coin never settles: it rattles straight on and drops into the next tube as well, so a single fivepence is tallied as a fivepence and a tenpence both. That is fall-through, and it is silent -- nothing jams, nothing rings a bell, the count is simply wrong. Worse yet, the slots judge a coin by its diameter alone and not by its metal. A worthless slug filed down to twenty millimetres sails through the twenty-millimetre slot exactly as a real coin would, because the slot only ever asked "are you this wide?" and never "are you genuine?". A switch compares with loose equality in the same spirit: it asks whether the values look equal, not whether they are truly the same kind, so a string can drop cleanly through a slot that was cut for an integer.


Syntax or Core Structure

A switch takes one subject value and compares it, in order, against a list of case labels. The first label that matches loosely (with ==) hands control to its body, and execution then runs forward -- through any labels beneath it -- until it reaches a break, a return, or the closing brace. Stacking several case labels with no code between them lets them share a single body, and the optional default arm runs when no label matched.

<?php

function classify(int $code): string
{
    switch ($code) {
        case 200:
        case 201:
            return 'success';
        case 301:
        case 302:
            return 'redirect';
        case 400:
        case 401:
        case 403:
        case 404:
            return 'client';
        case 500:
            return 'server';
        default:
            return 'unknown';
    }
}

foreach ([200, 201, 302, 404, 500, 418] as $code) {
    echo str_pad((string) $code, 3), ' ', classify($code), "\n";
}

Each return here doubles as the exit, so no break is needed: the function leaves the instant a label matches. The stacked labels (200 with 201, the four client codes together) are deliberate groups sharing one outcome, and 418 -- a real but unhandled code -- falls through to default.

Output:

200 success
201 success
302 redirect
404 client
500 server
418 unknown

Because every arm ends in return, this switch cannot fall through by accident; the danger appears only when arms end in break -- or in nothing at all -- which the next sections examine closely.


Technical Depth: How switch Compares, Groups, and Falls Through

switch against its younger sibling, match

PHP 8.0 introduced match, an expression that looks superficially like switch but repairs its two sharpest edges. Knowing where the two diverge tells you which to reach for, and it clarifies what switch actually does by contrast.

Aspectswitchmatch (PHP 8.0+)
Comparison operatorLoose, ==Strict, ===
Fall-throughYes, runs on until breakNo, exactly one arm runs
Is it an expressionNo, it is a statementYes, it yields a value
No arm matchesUses default, else does nothingThrows \UnhandledMatchError if there is no default
Grouping labelsStacked case labelsComma-separated conditions in one arm
Arm bodyAny number of statementsA single expression

The row that causes the most real bugs is the first: switch compares with ==, so case 0 will happily catch a value that merely looks like zero, while match (true) would not. The second row is the other classic trap: forget a break and switch keeps going, whereas match physically cannot. When every arm simply maps an input to one value, match is safer and shorter. Reach for switch when an arm needs several statements, or when you genuinely want grouped labels or intentional fall-through.

Fall-through: the same mechanism, used well and used badly

Fall-through is not a bug in itself -- stacked labels rely on it. The danger is that the deliberate version (empty labels sharing a body) and the accidental version (a real body with a forgotten break) look almost identical. The program below shows both in one switch:

<?php

function tag(int $n): string
{
    $hit = [];
    switch ($n) {
        case 1:
        case 2:
            $hit[] = 'low';
            break;
        case 3:
            $hit[] = 'three';
            // no break here -- execution falls through into case 4
        case 4:
            $hit[] = 'four';
            break;
        default:
            $hit[] = 'other';
    }
    return implode('+', $hit);
}

foreach ([1, 2, 3, 4, 9] as $n) {
    echo $n, ' -> ', tag($n), "\n";
}

Labels 1 and 2 share a body on purpose: both append low and break cleanly. Label 3 appends three and then, lacking a break, spills into label 4 and appends four as well -- so the input 3 produces three+four. Reading the code, you cannot tell whether that missing break was a clever choice or a typo, which is precisely why fall-through has such a poor reputation.

Output:

1 -> low
2 -> low
3 -> three+four
4 -> four
9 -> other

The loose comparison behind every case

A switch compares the subject to each label with ==, never ===. Most of the time this is invisible, but it bites the moment the subject is a string and a label is an integer. The classic pattern switch ($input) { case 0: ... } deserves close study, because before PHP 8 it matched almost any non-numeric string, and even now it behaves in a way that surprises people.

<?php

function reachesZeroArm(string $input): string
{
    switch ($input) {
        case 0:
            return 'matched case 0';
        default:
            return 'fell to default';
    }
}

foreach (['0', '', 'abc', '1e1'] as $input) {
    echo str_pad('"' . $input . '"', 6), ' -> ', reachesZeroArm($input), "\n";
}

Under PHP 8 the comparison $input == 0 follows a repaired rule: if the string is numeric, it is compared as a number; otherwise the integer 0 is turned into the string "0" and the two are compared as text. So "0" matches (numeric, equals zero), but "" and "abc" no longer do -- a change from PHP 7, where both slipped into the zero arm and caused years of quiet bugs. The numeric string "1e1" is read as the number 10, which is not zero, so it also falls through.

Output:

"0"    -> matched case 0
""     -> fell to default
"abc"  -> fell to default
"1e1"  -> fell to default

The lesson is not to memorise the table but to distrust switch whenever the subject and the labels are of different types. If you are switching on a string, make the labels strings; if the values must match by type, use match instead, which would send every one of these inputs to its default because === treats "0" and 0 as different.


Real World Example: A Cash Drawer Denomination Counter

At close of trade, a shop till is counted by feeding each denomination through a routine that recognises the coin or note by its code and files it under a class -- copper, silver, pound, or note -- summing both the piece count and the value as it goes. Anything unrecognised, a foreign coin or a filed-down slug, is diverted to a reject tally and left out of the banking total. A switch is the natural shape for that classification.

<?php

/** Map a denomination code to its class; the default arm rejects the unknown. */
function classOf(string $code): string
{
    switch ($code) {
        case '1p':
        case '2p':
            return 'copper';
        case '5p':
        case '10p':
        case '20p':
        case '50p':
            return 'silver';
        case '1pound':
        case '2pound':
            return 'pound';
        case '5note':
        case '10note':
        case '20note':
            return 'note';
        default:
            return 'reject';
    }
}

$unitPence = [
    '1p' => 1, '2p' => 2, '5p' => 5, '10p' => 10, '20p' => 20, '50p' => 50,
    '1pound' => 100, '2pound' => 200, '5note' => 500, '10note' => 1000,
    '20note' => 2000, 'slug' => 0,
];

$counted = [
    '1p' => 40, '2p' => 30, '5p' => 25, '10p' => 18, '20p' => 22, '50p' => 9,
    '1pound' => 14, '2pound' => 6, '5note' => 8, '10note' => 5, '20note' => 2,
    'slug' => 2,
];

$rank = ['copper' => 0, 'silver' => 1, 'pound' => 2, 'note' => 3];
$pieces = ['copper' => 0, 'silver' => 0, 'pound' => 0, 'note' => 0];
$value  = ['copper' => 0, 'silver' => 0, 'pound' => 0, 'note' => 0];
$grand = 0;
$rejected = 0;

foreach ($counted as $code => $count) {
    $class = classOf($code);
    if ($class === 'reject') {
        $rejected += $count;
        continue;
    }
    $pieces[$class] += $count;
    $value[$class]  += $unitPence[$code] * $count;
    $grand += $unitPence[$code] * $count;
}

printf("%-7s %6s %9s\n", 'CLASS', 'PIECES', 'VALUE');
echo str_repeat('-', 24), "\n";
uksort($pieces, fn($a, $b) => $rank[$a] <=> $rank[$b]);
foreach ($pieces as $class => $n) {
    printf("%-7s %6d %9.2f\n", $class, $n, $value[$class] / 100);
}
echo str_repeat('-', 24), "\n";
printf("%-7s %6d %9.2f\n", 'TOTAL', array_sum($pieces), $grand / 100);
echo "rejected {$rejected} foreign pieces (not counted)\n";

Output:

CLASS   PIECES     VALUE
------------------------
copper      70      1.00
silver      74     11.95
pound       20     26.00
note        15    130.00
------------------------
TOTAL      179    168.95
rejected 2 foreign pieces (not counted)

The stacked case labels do the real work here: eleven distinct codes collapse into four classes, and the default arm turns the single slug entry into a reject rather than crashing or miscounting. Every arm returns immediately, so there is no break to forget and no fall-through to trace. The value column is summed in whole pence and divided by one hundred only at the moment of printing, which keeps the arithmetic exact -- the copper class, seventy coins of one and two pence, comes to exactly one pound.

This code is honest about the count but it carries a real design flaw worth naming plainly. The denomination codes live in three separate places -- the switch in classOf, the $unitPence map, and the $counted tally -- with nothing keeping them in step. Add a fifty-pound note tomorrow and you must remember to touch all three; miss the switch and the note is silently rejected, miss $unitPence and PHP reads the undefined key as zero, so the note is counted as worthless with no error raised. A single source of truth -- one table mapping each code to its class and unit value, iterated everywhere -- would make the switch unnecessary and the whole routine impossible to leave half-updated. As written, correctness depends on a human editing three lists in lockstep, which is exactly the kind of quiet obligation that fails on a busy day.


Common Mistakes

  1. Forgetting break at the end of a case. This is the signature switch bug: execution runs straight on into the next case, so one input triggers two or more arms. It raises no error and often stays hidden until a specific value reveals it. Every arm that is not meant to fall through needs a break, a return, or a throw.
  1. Expecting strict comparison. A switch matches with ==, not ===, so case 0 can catch a numeric string and case "1" can catch the integer 1. If the values must match by type as well as content, use match, whose === comparison never crosses the type boundary.
  1. Using continue inside a switch to skip a loop. Inside a switch, continue is treated exactly like break -- it leaves the switch, not the surrounding loop -- and PHP even emits a warning. To skip the current iteration of the loop that wraps the switch, you must write continue 2.
  1. Placing default in the middle without a break. default need not be last, but if you position it among the cases and forget its break, control falls through into whatever case is written next. Keeping default at the end sidesteps the whole hazard.
  1. Writing duplicate case labels. Only the first occurrence of a given label is ever reached; any later case with the same value is dead code that silently never runs. PHP does not warn, so the mistake hides until someone wonders why an arm has no effect.
  1. Switching on a value whose type you have not pinned down. A subject that is sometimes an integer and sometimes a numeric string will match integer labels through loose comparison in ways that are hard to predict -- "1e1" equals 10, "0" equals 0. Normalise the subject to one type before the switch, or switch on strings throughout.
  1. Ordering a switch (true) from general to specific. The switch (true) idiom runs the first arm whose condition is true, so a broad test placed early shadows every narrower test below it. Arrange the conditions from most specific to most general, exactly as you would a chain of if / elseif.
  1. Trying to use switch as an expression. switch is a statement and yields no value, so $label = switch ($n) { ... }; is a syntax error. The construct that returns a value is match; reach for it whenever you were about to assign the result of a switch to a variable.
  1. Comparing arrays or objects in a case. Because the comparison is ==, two arrays match when they have the same keys and values, and two objects match when they are instances of the same class with equal properties -- rarely what a case label is meant to express. For identity or type-exact matching, compare explicitly with === in an if, or use match.

Best Practices

  • Prefer match over switch when each arm simply maps an input to a value: it compares strictly, cannot fall through, and returns a result, eliminating three whole classes of bug at once.
  • End every arm with break, return, or throw, and when you do want fall-through, mark it with an explicit comment such as // falls through so a reader knows the omission was deliberate.
  • Keep case labels the same type as the subject you are switching on -- string labels for a string subject, integer labels for an integer -- so loose comparison never has a type gap to exploit.
  • Always include a default arm, and place it last. Even if you believe every value is handled, default documents the intended catch-all and guards against inputs you did not foresee.
  • Express shared outcomes with stacked case labels rather than copying the same body into several arms; one edit then updates every label that shares it.
  • Keep each arm's body short. If a case grows past a few lines, move its work into a named function and call that from the arm, so the switch stays a readable table of decisions.
  • When you use switch (true) as a stand-in for an if / elseif chain, order the conditions from most specific to most general, because the first true one wins.
  • For a fixed, known set of cases, model the set as an enum and branch on it with match; the compiler-checked completeness beats a switch that silently ignores an unlisted value.

Practice Exercises

  1. Extend the HTTP classify function to recognise the 2xx codes 202 and 204 as success and the 3xx code 307 as redirect, using stacked case labels. Then add 429 as its own arm returning rate-limited, and confirm that an unlisted code such as 418 still reaches default.
  1. You are handed a switch where the input 3 mysteriously produces the combined output of two arms. Reproduce the bug with a small program, identify the missing break, and fix it so each input triggers exactly one arm -- then add a deliberate, commented fall-through elsewhere to show you can tell the two apart.
  1. Take a switch ($status) that classifies string statuses ("open", "closed", "pending") and rewrite it as a match expression assigned to a variable. Feed it a status that is not listed and observe the \UnhandledMatchError; then add a default arm and compare the behaviour to the original switch's silent default.
  1. Refactor the cash drawer counter to remove its design flaw: build one table that maps each denomination code to both its class and its unit value in pence, then derive the class and the value from that single table instead of from a switch and a separate map. Verify the totals still read 179 pieces and 168.95 before comparing the two versions for how many places you must edit to add a new denomination.