PHP match
PHP 8.0 introduced match, a modern alternative to switch. It is an expression, which means it produces a value you can assign, return or echo. It also compares strictly and never falls through, which removes the two most common switch bugs.
Basic syntax
$result = match ($value) {
pattern1 => expression1,
pattern2, pattern3 => expression2,
default => fallback,
};Each arm has one or more conditions on the left of => and a single expression on the right. Note the trailing semicolon after the closing brace — the whole thing is an expression statement.
<?php
$status = 404;
$message = match ($status) {
200 => "OK",
301, 302 => "Redirect",
404 => "Not Found",
500 => "Server Error",
default => "Unknown status",
};
echo "$status: $message\n";404: Not Found
match vs switch
switch |
match |
|
|---|---|---|
| Kind | statement | expression (returns a value) |
| Comparison | loose == |
strict === |
| Fall-through | yes, needs break |
never |
| Multiple values per branch | stacked case labels |
comma-separated |
| Body | any number of statements | one expression |
| No matching branch | nothing happens | throws UnhandledMatchError |
Strict comparison
Because match uses ===, a string never matches an integer arm. This is usually what you want with data from forms or URLs, which always arrives as strings:
<?php
function describe(mixed $v): string {
return match ($v) {
1 => "the integer one",
"1" => "the string one",
true => "boolean true",
default => "something else",
};
}
echo describe(1), "\n";
echo describe("1"), "\n";
echo describe(true), "\n";
echo describe(1.0), "\n";the integer one
the string one
boolean true
something else
With switch, all four calls would have hit the first case.
UnhandledMatchError
If no arm matches and there is no default, match throws an UnhandledMatchError. That is a feature: a silently ignored value is often a bug, and the exception points straight at it. You can catch it like any other exception:
<?php
function sizeLabel(string $code): string {
return match ($code) {
"S" => "Small",
"M" => "Medium",
"L" => "Large",
};
}
foreach (["M", "XL"] as $code) {
try {
echo $code, " -> ", sizeLabel($code), "\n";
} catch (\UnhandledMatchError $e) {
echo "Error: ", $e->getMessage(), "\n";
}
}M -> Medium
XL -> Error: Unhandled match case 'XL'
Notice that XL -> was already printed before the exception happened: echo with commas outputs each argument in turn.
match (true) for ranges
match arms compare against values, so to test ranges you match against true and write conditions on the left. The first arm whose condition is true wins:
<?php
function bmiCategory(float $bmi): string {
return match (true) {
$bmi < 18.5 => "underweight",
$bmi < 25.0 => "healthy",
$bmi < 30.0 => "overweight",
default => "obese",
};
}
foreach ([17.2, 22.0, 27.9, 33.1] as $bmi) {
printf("%.1f is %s\n", $bmi, bmiCategory($bmi));
}17.2 is underweight
22.0 is healthy
27.9 is overweight
33.1 is obese
Arms can call functions or throw
The right-hand side can be any expression, including a function call or (since PHP 8.0) a throw expression:
$price = match ($plan) {
"free" => 0,
"pro" => calculateProPrice($seats),
default => throw new InvalidArgumentException("Unknown plan: $plan"),
};Tip: Reach for
matchwhenever a branch just produces a value. Useswitchorifwhen each branch needs several statements.
Test yourself
What does match do when no arm matches and there is no default?
- Returns
null - Returns
false - Throws
UnhandledMatchError - Runs the first arm
What is printed by echo match("5") { 5 => 'int', default => 'other' };?
intother- Nothing
- An error
How do you let one match arm handle several values?
- Stack multiple
caselabels - Separate the values with commas
- Use
||between values - Omit
break