Match Expressions
A match expression picks one value by comparing a subject against a list of arms. It returns the picked value, so a program can save it or print it.
A status code picks a label
The subject is the code 200. The first arm fits, so the label holds the text OK.
<?php
$code = 200;
$label = match($code) {
200 => "OK",
404 => "Missing",
default => "Unknown",
};
echo $label . "\n";Several values share one arm
The count 3 sits in the shared arm with 2. Both values give the same result word.
<?php
$count = 3;
$word = match($count) {
1 => "one",
2, 3 => "few",
default => "many",
};
echo $word . "\n";Match compares strictly
The subject is the string "1", not the number 1. Strict comparison skips the number arm and picks the string arm.
<?php
$result = match("1") {
1 => "number",
"1" => "string",
default => "other",
};
var_dump($result);No fitting arm throws an error
The subject 9 fits no arm and the match has no default arm. The catch block prints the error class and its message.
<?php
try {
$label = match(9) {
1 => "one",
2 => "two",
};
echo $label . "\n";
} catch (UnhandledMatchError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}Example
<?php
$day = 6;
$kind = match($day) {
1, 2, 3, 4, 5 => "weekday",
6, 7 => "weekend",
default => "unknown",
};
echo "Day " . $day . " is a " . $kind . "\n";Key points
- A match expression starts with the word match and a subject in parentheses.
- Each arm pairs a value with a result, and an arrow joins the pair.
- Match compares with strict equality, so the value and the type must both fit.
- A switch statement compares loosely, so a switch and a match can pick different results.
- Several values can share one arm when they sit in one comma list.
- The default arm gives the result when no other arm fits.
- A match with no fitting arm and no default arm throws an UnhandledMatchError.
In this example, the subject is the day number 6. The first arm lists the five weekday numbers and does not fit. The second arm lists 6 and 7, so the match returns the word weekend for the print line.
Note
Match is an expression, so its result can sit inside an assignment or an echo call.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A match subject is the string "1" and the arms hold the number 1 and the string "1". Which arm wins?