match picks a result by comparing one value against a list of options. It arrived in PHP 8.0, and it is usually cleaner than a long if chain or a switch.
<?php
$status = 2;
$label = match ($status) {
1 => "Pending",
2 => "Shipped",
3 => "Delivered",
};
echo $label;
Shipped
match is an expression: it gives back a value that you can store or print, so you do not need to assign in every branch.
A default arm
Add default for values that match nothing.
<?php
$code = 404;
echo match ($code) {
200 => "OK",
301, 302 => "Redirect",
404 => "Not found",
default => "Unknown",
};
Not found
You can list several values for one result, separated by commas (301, 302).
No match, no default: an error
If nothing matches and there is no default, PHP throws an UnhandledMatchError. That is on purpose. It tells you about a case you forgot.
<?php
try {
echo match (5) {
1 => "one",
2 => "two",
};
} catch (\UnhandledMatchError $e) {
echo $e->getMessage();
}
Unhandled match case 5
Strict comparison
match uses ===, so "1" does not match 1. This removes a whole group of switch surprises.
<?php
$value = "1";
echo match ($value) {
1 => "integer one",
"1" => "string one",
default => "other",
};
string one
No fall-through
In a switch, you must write break after each case, or the code runs into the next one. match has no fall-through and needs no break.
Matching conditions with match(true)
A common trick is to match against true and write conditions as the arms.
<?php
$score = 82;
$grade = match (true) {
$score >= 90 => "A",
$score >= 75 => "B",
$score >= 60 => "C",
default => "F",
};
echo $grade;
B
The arms are checked from top to bottom, and the first true one wins.
Each arm is one expression
An arm holds a single expression, not a block of statements. For more complex work, call a function.
<?php
function describe(string $day): string
{
return match ($day) {
"Sat", "Sun" => "Weekend",
default => "Weekday",
};
}
echo describe("Sun");
Weekend
Needs PHP 8.0
match is a parse error on PHP 7. If your host is that old, see PHP Versions and ask about an upgrade.