match
The match expression returns one value from the first arm whose condition is strictly identical to the subject, has no fall-through, and throws an error when nothing matches.
Compare match's strict comparisons and returned value with switch behavior.
The delivery switch from the last lesson took eleven lines, needed two breaks, and would quietly set null for a format nobody expected. PHP 8 added match, a tighter tool for the most common job of switch: turning one value into another.
The rule
match returns one value, compares strictly, and fails loudly on no match.
<?php
$format = "hardback";
$delivery = match ($format) {
"paperback", "hardback" => 3.50,
"ebook", "audio" => 0,
};
echo $delivery; // 3.5What makes match different from switch:
- It is an expression. It produces a value, so you assign it, return it or echo it directly.
- Each arm is
conditions => result. Several conditions can share an arm, separated by commas. - No fall-through, no
break. Exactly one arm's result is used. - Strict comparison (
===).match ("1")does not match an arm for the integer1. - No match is an error. If nothing fits and there is no
defaultarm, PHP throws anUnhandledMatchError. A typo such as"hardbak"gets noticed at once instead of quietly producingnull.
Add a default arm when a fallback really is correct:
$delivery = match ($format) {
"paperback", "hardback" => 3.50,
"ebook", "audio" => 0,
default => 5.00, // any other physical item
};Ranges with match (true). Arms can be any expression, and each is compared with the subject. Put true in the subject and the first arm whose condition is true wins:
$label = match (true) {
$stock === 0 => "Sold out",
$stock < 5 => "Only a few left",
default => "In stock",
};This replaces the if/elseif chain for labels, and the narrowest-first rule still applies.