Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 147 ยท Control Flow

switch and match

Learn PHP switch and the PHP 8 match expression - fall-through and break, loose versus strict comparison, returning values, UnhandledMatchError and match(true) patterns.

When one value can lead to many different outcomes, a long if/elseif chain that compares the same variable again and again gets tedious: if ($status === 'draft') ... elseif ($status === 'review') ... elseif ($status === 'published') .... PHP has two dedicated tools for this: the classic switch statement, which PHP inherited from C, and the match expression, added in PHP 8.0.

They look similar but behave very differently. switch runs blocks of statements, falls through from one case to the next unless you stop it, and compares loosely with ==. match produces a value, never falls through, compares strictly with ===, and throws an error if nothing matches. This lesson covers both in depth, then shows the match(true) pattern that replaces many elseif chains, and ends with advice on choosing between them. You should already know if, elseif and else and the difference between == and === from Comparison Operators.

The switch statement

A switch compares one value against a list of case labels. PHP jumps to the first matching label and runs the statements from there:

PHP
switch (expression) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    default:
        // runs when no case matched
}
PHP A basic switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice two things. First, break ends the switch; PHP continues with the line after the closing brace. Second, case 'sat': has no statements of its own. That's how you give several values the same code: stack the labels, and a match on any of them runs the shared block. The default label handles every value that no case matched. It's optional, but it's a good place to catch unexpected input.

Fall-through: the missing break

case labels are only entry points. Once PHP has jumped to a matching case, it runs every statement below it, straight through the following labels, until it reaches a break or the end of the switch. This is called fall-through. Forget one break and code that was meant for another case runs too:

PHP A forgotten break falls through

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The express order promises two delivery dates, because execution fell from the express case into the standard one. PHP gives no warning. Occasionally fall-through is useful on purpose, for example when each case adds one step on top of the next, but then you should say so with a comment like // fall through so readers know it isn't a bug.

Tip: Inside a function, you can use return instead of break in each case. Returning leaves the function, so nothing can fall through, and the code gets shorter. You'll see this style often in real projects.

switch compares loosely

switch uses ==, not ===. The value and each case are compared with PHP's loose comparison rules, including type conversion. Sometimes that's convenient, because the string '2' from a form matches case 2. Often it hides bugs:

PHP Loose comparison in switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

true, '1' and '1.0' all land in the 1 case, and '', false and 0 all count as null. The function's mixed parameter type just means "any type"; Type Declarations explains it. PHP 8 removed the worst surprise (in PHP 7, 0 matched case 'abc' because 'abc' was converted to 0), but loose matching is still a common source of subtle bugs, especially with null, false, 0 and empty strings.

A widely used workaround is switch (true), where each case is a full condition. It works, but match(true), shown below, does the same job with strict comparison and less code.

continue inside switch

In PHP, switch counts as a loop structure for break and continue. So a continue inside a switch that sits inside a loop doesn't continue the loop; it acts like break, and PHP warns about it at compile time: "continue" targeting switch is equivalent to "break". Write continue 2 to continue the enclosing loop. The levels after break and continue are explained in break, continue and Loop Control.

The match expression (PHP 8.0)

match was designed to fix everything awkward about switch. Here's the same weekday logic:

PHP
$message = match ($day) {
    'mon' => 'Start of the work week.',
    'fri' => 'Almost the weekend!',
    'sat', 'sun' => 'Weekend. Sleep in.',
    default => 'A regular weekday.',
};

Each line is an arm: one or more conditions separated by commas, then =>, then a single expression. The differences from switch are important:

switch match
Kind statement expression (produces a value)
Comparison loose == strict ===
Fall-through yes, unless you break never
Several values stacked case labels comma-separated conditions
Body any number of statements one expression per arm
No match nothing happens (or default) UnhandledMatchError (or default)

Because match is an expression, you can assign it, return it, pass it to a function or echo it. And note the semicolon after the closing brace: the whole match is part of an assignment statement.

PHP match returns a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

declare(strict_types=1); at the top tells PHP not to convert argument types silently when you call functions declared with types (here, int $code). It's a good habit in any script with functions, and Type Declarations covers it fully.

Strict comparison

match compares with ===, so both the value and the type must match. The string '1' doesn't match the integer 1:

PHP match compares strictly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each value lands in exactly one arm, and '' and 1.0 don't match anything except default, because there's no arm with an identical value and type. This is usually what you want with user input too: convert it to the right type once, then match strictly.

UnhandledMatchError

When no arm matches and there's no default, match throws an UnhandledMatchError. That sounds harsh, but it's a feature: an unexpected value fails loudly at the point where it appears, instead of quietly producing null and breaking something three steps later. This example fails on purpose for the third value:

PHP No arm matches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The message, Unhandled match case 'XX', includes the value that wasn't handled, which makes the bug easy to find. UnhandledMatchError extends PHP's Error class, so you can catch it with try/catch (see Exceptions), but usually the right fix is to handle the case, or to add a default arm that throws a more meaningful exception:

PHP
default => throw new InvalidArgumentException("No VAT rate for $country"),

Since PHP 8.0, throw is an expression, so it can appear in a match arm.

Arms are evaluated lazily

match checks the conditions from top to bottom and stops at the first identical one. Only the winning arm's result expression runs; the others are never evaluated. That means you can safely call functions in the arms:

PHP Only the chosen arm runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only (reading cache) appears. If an arm needs several statements, move them into a function and call it from the arm; that keeps the match readable.

match(true): replacing elseif chains

Matching against true turns each arm into a condition. PHP evaluates the conditions in order and picks the first one that is identical to true:

PHP Ranges with match(true)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

As with elseif, the order of the arms matters: a BMI of 17.2 is also below 25 and 30, but the first true arm wins. One subtle point: because the comparison is strict, each condition must produce a real boolean. A comparison like $bmi < 25 does. A function that returns 1 or a non-empty string does not match true, so wrap such calls in (bool) or compare explicitly (preg_match() returns 1, which is why the example negates it with !, producing a boolean).

Choosing between them

  • Use match when you're mapping a value to a result: status codes to labels, sizes to prices, enum cases to text (you'll do a lot of that in Class Constants and Enums). It's shorter, strict, and can't fall through.
  • Use match(true) for a small set of conditions that each produce a value, instead of an elseif chain that only assigns a variable.
  • Use if/elseif when the branches do several things, or when the conditions are unrelated.
  • Use switch mainly when you read or maintain older code, or when you genuinely need several statements per case and fall-through. If you write one, add a break (or return) to every case and a default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? $n = 2; switch ($n) { case 1: echo "a"; case 2: echo "b"; case 3: echo "c"; break; default: echo "d"; }

    PHP jumps to case 2 and falls through into case 3 because there's no break, then stops at the break. The default is never reached.
  2. 2. What does echo match ("5") { 5 => "int", "5" => "string", default => "other" }; print?

    match uses ===, so the string "5" only matches the arm with the string "5".
  3. 3. With $v = "";, which case does switch ($v) { case null: ... case "": ... } run?

    switch compares loosely with ==, and "" == null is true. The first matching case wins, so the null case runs.
  4. 4. What happens when no arm of a match expression matches and there is no default arm?

    An unhandled value throws UnhandledMatchError, with the value in the message. Add the missing arm or a default.
  5. 5. What is match (true) { 5 > 3 => "a", 10 > 3 => "b", default => "c" }?

    The arms are checked from top to bottom, and the first condition that is identical to true wins. match never falls through.

Summary

  • switch compares one value against case labels with loose == comparison and runs statements from the first match.
  • Without break (or return), switch falls through into the next case; stack labels deliberately to share code, and mark intentional fall-through with a comment.
  • Inside a loop, continue in a switch acts like break; use continue 2 to continue the loop.
  • match (PHP 8.0) is an expression that returns a value, compares strictly with ===, never falls through, allows comma-separated conditions and runs only the winning arm.
  • An unmatched value with no default throws UnhandledMatchError; throw can be used in an arm.
  • match(true) replaces elseif chains that produce values; each condition must evaluate to a real boolean.

Next: while, do-while and for Loops