The PHP Match Expression
The match expression provides a new way to handle multiple conditional checks (like the switch statement).
The match expression evaluates an expression against multiple alternatives (using strict comparison) and returns a value.
Tip: The
matchexpression is new in PHP 8.0.
Here are the key differences between match and switch:
- A
matchexpression has a more readable syntax thanswitch - A
matchexpression returns a value, whileswitchdoes not - A
matchexpression breaks automatically after a match, whileswitchrequiresbreak; - A
matchexpression has strict comparison (===), whileswitchuses loose comparison (==)
Syntax for match
$result = match($expression) {
condition1 => returnvalue1,
condition2 => returnvalue2,
condition3, condition4 => returnvalue3,
default => defaultvalue,
}
Tip: The default arm catches all expressions that are not matched.
The following example is equal to the example on the switch page, but here we use the match expression:
Example
$favcolor = "red";
$text = match($favcolor) {
"red" => "Your favorite color is red!",
"blue" => "Your favorite color is blue!",
"green" => "Your favorite color is green!",
default => "Your favorite color is neither red, blue, nor green!",
};
echo $text;
Match Multiple Values
If you want the match expression to match multiple values for the same code block, you can group them with commas, like this:
Example
Match multiple values:
$d = 3;
$text = match($d) {
1, 2, 3, 4, 5 => "The week feels so long!",
6, 0 => "Weekends are best!",
default => "Invalid day",
};
echo $text;
The default Keyword
In a match expression, there must be a condition that matches the expression, or a default case, to handle it.
If there are no matches, and no default case, the match expression throws an UnhandledMatchError exception.
Example
This will throw an UnhandledMatchError exception:
$favcolor = "pink"; // no conditions will match this
try {
$text = match($favcolor) {
"red" => "Your favorite color is red!",
"blue" => "Your favorite color is blue!",
"green" => "Your favorite color is green!",
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
echo $text;