The match expression branches evaluation based on an
identity check of a value.
Similarly to a switch statement, a
match expression has a subject expression that is
compared against multiple alternatives. Unlike switch,
it will evaluate to a value much like ternary expressions.
Unlike switch, the comparison is an identity check
(===) rather than a weak equality check (==).
Match expressions are available as of PHP 8.0.0.
<?php
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
The above example will output:
string(19) "This food is a cake"
Example #3 Example of using match with comparison operators
The result of a match expression does not need to be used.
Note:
When a match expression is used as a standalone
expression, it must be terminated
by a semicolon ;.
The match expression is similar to a
switch statement but has some key differences:
A match arm compares values strictly (===) instead
of loosely as the switch statement does.
A match expression returns a value.
match arms do not fall through to later cases the way
switch statements do.
A match expression must be exhaustive.
Like switch statements, match
expressions are executed match arm by match arm.
In the beginning, no code is executed.
The conditional expressions are only evaluated if all previous conditional
expressions failed to match the subject expression.
Only the return expression corresponding to the matching conditional
expression will be evaluated.
For example:
<?php
$result = match ($x) {
foo() => 'value',
$this->bar() => 'value', // $this->bar() isn't called if foo() === $x
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
// etc.
};
match expression arms may contain multiple expressions
separated by a comma. That is a logical OR, and is a shorthand for multiple
match arms with the same right-hand side.
<?php
$result = match ($x) {
// This match arm:
$a, $b, $c => 5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};
A special case is the default pattern.
This pattern matches anything that wasn't previously matched.
For example: