PHP match Expression
PHP 8.0 added the match expression, a close relative of switch. There are three main differences: it produces a value, it compares with strict comparison (===), and it needs no break statements.
Basic match expression
The value of $status decides which string match gives back, and that string is stored in $text:
Output: PHP script
<?php
$status = 1;
$text = match($status) {
1 => "Ready",
2 => "Set",
3 => "Go",
};
echo $text;
?>
The default Keyword
A default arm catches everything the other arms don't. It is worth adding, because if no arm matches and there is no default, PHP throws an UnhandledMatchError.
Match with default
No arm covers the value 5, so the default arm supplies the result:
Output: PHP script
<?php
$status = 5;
$text = match($status) {
1 => "Ready",
2 => "Set",
3 => "Go",
default => "Unknown",
};
echo $text;
?>
Multiple Values Per Arm
One arm can cover several values: write them separated by commas. That arm is chosen if the expression matches any one of them.
Match with multiple values
Here the days are grouped into three arms, with commas between the values in each:
Output: PHP script
<?php
$day = 2;
$text = match($day) {
1, 2 => "Weekday start",
3, 4, 5 => "Mid/late weekday",
6, 7 => "Weekend",
};
echo $text;
?>
Strict Comparison
Because match compares with ===, a value must have the right data type as well as the right content. A switch statement is more relaxed, since it compares loosely (==).
Match strict comparison
The string "1" fails to match the integer 1 under strict comparison, so the default arm is used:
Output: PHP script
<?php
$status = "1";
$text = match($status) {
1 => "Integer match",
default => "No match",
};
echo $text;
?>