Introduced in PHP 8.0, the match expression is a more powerful and concise version of the switch statement. It allows you to select a value based on a condition and returns that value directly to a variable or into an output.
Unlike switch, match uses a comma-separated syntax and doesn't require break or case keywords.
<?php
$food = "cake";
$return_value = match ($food) {
"apple" => "This food is a fruit",
"bar" => "This food is a candy bar",
"cake" => "This food is a dessert",
default => "Unknown food",
};
echo $return_value; // Outputs: This food is a dessert
?>
The match expression fixes several "weird" behaviors of switch:
| Feature | Switch | Match |
|---|---|---|
| Category | Statement | Expression (returns a value) |
| Comparison | Loose (==) |
Strict (===) |
| Break | Required to stop fall-through | Implicit (no fall-through) |
| Multiple values | Requires multiple case blocks |
Comma-separated on one line |
You can match multiple search values to a single result arm easily:
<?php
$age = 15;
$result = match (true) {
$age >= 18 => "Adult",
$age < 18 => "Minor",
};
echo $result;
?>
match uses ===. This
means "10" will NOT match an integer 10. This makes your code
significantly safer and less prone to type-related bugs.
match expression must be
exhaustive. If no default is provided and no match is found, PHP will throw
an UnhandledMatchError.