Explain it simply
Explain it simply
Think of switch as picking a door by reading the signs. It takes one value, such as an order's status, compares it with each case in turn and opens the first door that fits. It suits any job where one value is checked against many options: roles, payment states, menu choices.
However, once a door is open, execution keeps walking through the next doors unless a break closes it; that is called fall-through. PHP 8 added a new expression, match, which does not have this problem. Let us compare the two.
Problem → Why → Solution
The problem: a missing break prepares an unpaid order
The order status is "pending", meaning unpaid. The first case is missing its break, so after printing "Waiting for payment" PHP keeps running the code of the next case, "paid". A message to prepare an unpaid order is a bug that can lose money, yet nothing raises an error.
<?php
$status = "pending";
switch ($status) {
case "pending":
echo "Waiting for payment" . PHP_EOL;
// forgot: break;
case "paid":
echo "Prepare the order" . PHP_EOL;
break;
default:
echo "Unknown status" . PHP_EOL;
}Why do both lines print?
switch finds the first matching case label and starts running from there, then keeps running every line below it until it meets break, return, exit or the end of the switch. Later case labels do not say "stop here"; they are only entry points. So end every case with break, or use match instead.
Core concept: switch versus match
switch compares one subject against a list of case values and runs the code under the first case that matches. default runs when nothing matches. It is tidier than a long elseif chain when every branch tests the same variable for equality: roles, order statuses, menu choices, file extensions. The subject is evaluated only once, so a function call inside switch (...) runs a single time, and each case value can itself be an expression.
Two properties make switch tricky. First, the comparison is loose (==), so switch ('1') matches case 1 and case '1e1' matches '10'; null, false, 0 and '' also match each other, so switch (null) { case false: ... } runs. Second, execution falls through: after a match PHP keeps running the following case bodies until it meets break (or return, exit, throw). Stacking case 'sat': case 'sun': to share one body is a deliberate use, but forgetting break is one of the most common bugs and there is no warning.
PHP 8.0 added match to fix these quirks. match is an expression: it compares strictly (===), never falls through, and returns a value you can assign or echo. One arm can list several comma-separated conditions, and when nothing matches and there is no default it throws UnhandledMatchError. A message such as "Unhandled match case 'refunded'" names the status you forgot. Because every arm is a single expression, match suits code that maps values; when a case needs several statements, use switch or if.
| Aspect | switch | match |
|---|---|---|
| Comparison | loose (==) | strict (===) |
| Fall-through | yes (needs break) | never |
| Returns a value | no, it is a statement | yes, it is an expression |
| No match, no default | silently skipped | UnhandledMatchError |
| Per arm | many statements | one expression |
- Evaluate the subject once
- Jump to the first matching case
- switch keeps running until break
- match returns one arm and stops
In switch the case labels are only entry points; break is the exit.
General pattern
<?php
switch ($subject) {
case valueA:
case valueB: // A and B share one body
doSomething();
break;
default:
doFallback();
}
$result = match ($subject) { valueA, valueB => resultOne, default => resultTwo };In switch every case needs its own break, and stacked case labels share one body. In match each arm returns one value with =>, and even when it fits on one line the closing brace needs a semicolon after it.
Example: showing a message for a payment status
This example compares the status with each case and prints the right message. Notice that every case ends with break and that default catches unknown statuses.
<?php
$status = "paid";
switch ($status) {
case "pending":
echo "Payment is still pending.";
break;
case "paid":
echo "Payment received. Prepare the order.";
break;
case "cancelled":
echo "Order was cancelled.";
break;
default:
echo "Unknown payment status.";
}
?>Code breakdown
- Line 4
switch ($status) {$status is evaluated once and compared with the cases from top to bottom, using loose (==) comparison.
- Line 8
case "paid":"paid" == "paid" matches, so execution starts here. The "pending" case above did not match and was skipped.
- Line 9
echo "Payment received. Prepare the order.";This is the work of the matching case: it prints the message, which is the lesson's expected output.
- Line 10
break;break leaves the whole switch. Without it PHP would go on to print the "cancelled" message as well.
- Line 14
default:When no case matches, this branch runs. It is the safe place to handle unexpected statuses, and by convention it goes last.
Payment received. Prepare the order.Falling through on purpose
There are places where fall-through is genuinely useful, for example when a level 3 user also gets every feature of levels 2 and 1. Where you leave out break on purpose, say so in a "no break" comment so the next reader does not take it for a bug.
<?php
function describeLevel(int $level): string
{
$features = [];
switch ($level) {
case 3:
$features[] = "admin panel";
// no break: level 3 also gets the level 2 features
case 2:
$features[] = "reports";
// no break: level 2 also gets the level 1 features
case 1:
$features[] = "dashboard";
break;
default:
$features[] = "login page";
}
return implode(", ", $features);
}
echo describeLevel(3) . PHP_EOL;
echo describeLevel(2) . PHP_EOL;
echo describeLevel(1) . PHP_EOL;
echo describeLevel(0) . PHP_EOL;continue inside a switch
Inside a loop, continue in a switch only leaves the switch (like break) and does not jump to the loop's next iteration. PHP warns about it: Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Use continue 2 when you want the loop to move on.
match: strict, no fall-through, returns a value
In the first snippet below, switch says "1e1" matches case "10", while match needs identical values and falls to its default. That hidden difference matters in security and pricing logic. The second snippet uses match directly in a return and catches the UnhandledMatchError for an unexpected value such as "refunded".
<?php
$input = "1e1"; // text typed by a user
switch ($input) {
case "10":
echo "switch: ten" . PHP_EOL; // runs, because "1e1" == "10" is true
break;
default:
echo "switch: no match" . PHP_EOL;
}
$result = match ($input) {
"10" => "match: ten",
default => "match: no match",
};
echo $result . PHP_EOL;<?php
function statusMessage(string $status): string
{
return match ($status) {
"pending" => "Payment is still pending.",
"paid", "shipped" => "Payment received.",
"cancelled" => "Order was cancelled.",
};
}
echo statusMessage("paid") . PHP_EOL;
echo statusMessage("shipped") . PHP_EOL;
try {
echo statusMessage("refunded") . PHP_EOL;
} catch (\UnhandledMatchError $e) {
echo get_class($e) . ": " . $e->getMessage() . PHP_EOL;
}Checking ranges with match (true)
match needs identical values, so it cannot test ranges directly. But if you give it true as the subject and write bool-producing conditions in the arms (match (true) { ... }), the first arm that evaluates to true wins, from top to bottom, exactly like if/elseif but producing a value. The arm's expression must be a real bool: even a truthy string does not match, because the comparison with true is strict.
<?php
function gradeFor(int $score): string
{
return match (true) {
$score >= 90 => "A",
$score >= 80 => "B",
$score >= 60 => "C",
default => "F",
};
}
foreach ([95, 82, 60, 59] as $score) {
echo "$score => " . gradeFor($score) . PHP_EOL;
}In real projects
Where this shows up in real projects
A router that looks at ?page=home and decides which file to load, a mapper from HTTP status codes to messages, a choice of e-mail template by order status and a lookup of the MIME type from a file extension are all jobs of choosing one result from one value. Written with match they become a single assignment such as $mime = match ($ext) { ... };.
In code that handles order states such as pending, paid and shipped, a match without default is a useful safety net: if you add a new status and forget to handle it, UnhandledMatchError tells you at once instead of being skipped silently as in a switch. match also pairs naturally with PHP 8.1 enums. For input that comes from outside in production, however, add a default arm and show a friendly error message.
Common mistakes
Common mistakes
1. Forgetting break
A missing break lets the next case's code run too, and PHP raises no warning. When you fall through on purpose, add a "// no break" comment, or use return instead.
2. Assuming switch is strict
switch ('10') { case '1e1': ... } matches, and null also matches case false. For values that must be exact, such as IDs, tokens and prices, use match, or check and convert the value's type before the switch.
3. Using match on user input without a default
match ($_GET['page']) { 'home' => ..., 'about' => ... } throws UnhandledMatchError and breaks the page when it receives something unplanned such as 'contact'. For outside input add a default arm or use a catch.
4. Forgetting the semicolon after a match expression
Leaving the semicolon off $r = match (...) { ... } produces an error on the next line such as Parse error: syntax error, unexpected token "echo". match is an expression, not a statement, so it ends with ; like any assignment.
Best practices
Best practices
- Prefer match when you map one value to another, and keep switch for cases that need several statements.
- In a switch, end every case with break or return, mark intentional fall-through with a comment and always include default.
- Use match (true) for ranges, and give match a default arm when the value comes from outside.
Mini challenge
Mini challenge: an HTTP status helper
Write two functions for HTTP status codes: statusText() maps a code to its text and statusClass() puts it into a group. statusText() must throw UnhandledMatchError for an unknown code, which you then catch and show as "Unknown code".
- statusText(int $code): string — use match: 200 OK, 201 Created, 301 and 302 Redirect, 404 Not Found, 500 Server Error, and no default
- statusClass(int $code): string — use match (true) to return success, redirect, client error, server error or unknown by range
- Loop over the codes 200, 301, 404, 418 and 500 with try/catch and print each as "CODE TEXT (CLASS)"
- Do not use switch; match has no break to forget
<?php
function statusText(int $code): string
{
// TODO: match ($code) with 200, 201, 301 and 302 sharing one arm, 404, 500
// and deliberately no default arm
}
function statusClass(int $code): string
{
// TODO: match (true) with range conditions and a default arm
}
// TODO: loop over the codes, wrap statusText() in try/catch for UnhandledMatchErrorExpected: Expected output: 200 OK (success) 301 Redirect (redirect) 404 Not Found (client error) 418 Unknown code (client error) 500 Server Error (server error)
Show hint
Put 301, 302 => "Redirect" into one arm with a comma. In match (true) each arm must produce a bool such as $code >= 200 && $code < 300. In the catch block write the class as \UnhandledMatchError.
Show solution
<?php
function statusText(int $code): string
{
return match ($code) {
200 => "OK",
201 => "Created",
301, 302 => "Redirect",
404 => "Not Found",
500 => "Server Error",
};
}
function statusClass(int $code): string
{
return match (true) {
$code >= 200 && $code < 300 => "success",
$code >= 300 && $code < 400 => "redirect",
$code >= 400 && $code < 500 => "client error",
$code >= 500 && $code < 600 => "server error",
default => "unknown",
};
}
foreach ([200, 301, 404, 418, 500] as $code) {
try {
$text = statusText($code);
} catch (\UnhandledMatchError $e) {
$text = "Unknown code";
}
echo "$code $text (" . statusClass($code) . ")" . PHP_EOL;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- switch compares loosely (==) and its case labels are only entry points, so a missing break causes fall-through.
- match compares strictly (===), never falls through, returns a value and throws UnhandledMatchError when nothing matches.
- Check ranges with match (true); every arm must produce a bool.
- Choose match to map values and switch when you need several statements, and remember the ; after a match expression.
PHP Language Reference — PHP Documentation Group