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.
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 (==
).
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;
In this example:
$day
is the subject expression. Its value is compared with alternatives in the expression.
Fri
, Mon
and Sat
are 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 switch
statements, code in a match
expression is only run if conditions before it failed.
For example, the line "Sat" => "Enjoy your weekend"
isn’t executed.
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;
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.
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.
match
expressionCurrently, 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.
A match
expression throws an error (UnhandledMatchError
) if an input matches no alternative.
A match
expression must be terminated by a semi-colon.