PHP
The match expression
Learn to write shorter and safer conditionals than switch with the match expression.
What is the match expression?
PHP 8.0 added match as an expression: it produces a value you can assign to a variable. switch is a statement that does not return a value.
match compares with strict (===) equality; no type casting. Arms are separated by commas and bound to results with =>.
A match must cover every possible value; an unmatched input throws. A default arm prevents that.
default arm and the never return type
The default arm of match catches every unmatched value. Without it, an unmatched input throws UnhandledMatchError.
You can write an arm to throw: default => throw new \InvalidArgumentException(). In that case match returns no value.
PHP 8.1 adds the never return type. It marks methods that never return (always throw or call exit). Code after such a method never runs; the compiler knows this.
Exercise HTTP status label
Write http_status_label(int $code): string using match. Return "OK" for 200, "Not Found" for 404, "Server Error" for 500 and "Unknown" for default.
The call below should print Not Found.
Show example solution
function http_status_label(int $code): string {
return match($code) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown",
};
}
echo http_status_label(404);
Test yourself
-
What characterizes the match expression?
- It only works with integers
- It compares case-insensitively
- It returns an array automatically
- Unlike switch it returns a value and uses ===
Show answer
Unlike switch it returns a value and uses === — Correct. match returns a value as an expression and compares with strict (===) equality, unlike switch.
-
Complete the match arm
$status = match($code) {
200 => "OK",
404 => ____,
default => "Unknown",
};
Show answer
$status = match($code) {
200 => "OK",
404 => "Not Found",
default => "Unknown",
};
-
Match the match concepts
- match
- value-returning conditional
- default
- for unmatched values
- =>
- links condition and result
- ===
- strict equality comparison
Next lesson: Named arguments