What is the match expression in PHP?
The match expression is like a switch statement. It evaluates based on an identity-check of a value. It was introduced in PHP 8.0.0.
How does the match expression work?
The match expression has a subject expression that is passed to it. This expression is then compared against multiple alternatives.
Its comparison uses the strict identity check (===), rather than the weaker equality check (==).
Syntax
A match expression usually has the following structure:
$day = "Mon";
$test = match ($day) {
"Fri" => "How is your week going",
"Mon" => "Welcome to the new week",
"Sat" => "Enjoy your weekend"
};
echo $test;
Explanation
In this example:
-
$dayis the subject expression. Its value is compared with alternatives in the expression. -
Fri,MonandSatare alternatives that are compared against. -
The strings
"How is your week going","Welcome to the new week", and"Enjoy your weekend"are the return expressions.
-
This example outputs
"Welcome to the new week". -
Like
switchstatements, code in amatchexpression is only run if conditions before it failed. -
For example, the line
"Sat" => "Enjoy your weekend"isn’t executed.
Multiple expressions with the same output
Example 1
Sometimes, some expressions will have the same output. You can list them all out and repeat the expected response, like so:
$age = 12;
$test = match ($age) {
12 => "Very welcomed",
16 => "Very welcomed",
21 => "Very welcomed",
19 => "We don't want you"
};
echo $test;
Example 2
Or, you could use the short-hand and map them all to the same return statement, like this:
$age = 12;
$test = match ($age) {
12, 16, 21 => "Very welcomed",
19 => "We don't want you"
};
echo $test;
These two examples give the same output: "Very welcomed". However, the latter is shorter and easier to write.
How to set a default case
If no alternative is the same as the given input, it is good to have a default or fallback response.
To do this, simply add default to the alternatives like this:
$age = 4;
$test = match ($age) {
12, 16, 21 => "Very welcomed",
19 => "We don't want you",
default => "I don't know what to do with you"
};
echo $test;
In this example, our default response is outputted.
Handle non-identity checks with the match expression
Currently, it seems like the match expression is limited to comparing single values to simple alternatives. It can be used for more complex cases.
To use match for a non-identity check, set the subject expression to true (instead of any value).
For example, to give different discounts based on age range:
$price = 1000;
$age = 22;
$discount = match (true) {
$age <= 18 => $price * 0.5,
$age > 18 && $age <= 60 => $price * 0.1,
$age > 60 => $price * 0.7,
};
echo $discount;
This example checks the value of $age within a range and sets the discount based on that age range.
Things to note
-
A
matchexpression throws an error (UnhandledMatchError) if an input matches no alternative. -
A
matchexpression must be terminated by a semi-colon.