match
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.
The shortcut
Ask "am I choosing a value, or running different steps?" Choosing a value → match. Several statements per branch, or deliberate fall-through → switch or if.
Spot the pattern
Every case of the switch only sets
$delivery. It is choosing a value.
Drills
Answer fast — trust the rule.
What does match do when no arm matches and there is no default?
What is match ("1") { 1 => "int", default => "other" }?
How do two conditions share one arm?
With $stock = 2, what does the match (true) label example return?
Remember
- match returns one value, compares strictly, and fails loudly on no match.
- Shortcut: choosing a value → match; running several steps → if or switch.
- Trap: leaving out
defaultis a choice: it turns surprises into errors.
