The match expression in PHP
PHP 8's answer to switch: strict comparison, a return value, no fallthrough.
<?php
$status = 404;
// match compares with ===, returns a value, and never falls through
$label = match ($status) {
200, 204 => "success",
301, 302 => "redirect",
404 => "not found",
500 => "server error",
default => "unknown",
};
echo "$status: $label", PHP_EOL;
echo match (true) {
$status >= 400 => "trouble",
default => "fine",
}, PHP_EOL;
How it works
match ($status)compares each arm with===and yields the arm's value.- Commas group codes, so
200, 204share one label;defaultcatches the rest. match (true)turns the arms into arbitrary conditions, like range checks.
Keywords and builtins used here
defaultechomatchtrue
The run, in numbers
- Lines
- 17
- Characters to type
- 346
- Tokens
- 80
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 60 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.