- PHP
- syntax
Reach for match() instead of switch
match compares strictly, returns a value and throws on an unhandled case, which removes the three usual switch bugs in one move.
1 min read
switch uses loose comparison ('1' == 1), falls through when a break is missing, and silently does nothing for a value nobody expected. match fixes all three.
$label = match ($order->status) {
OrderStatus::Pending => 'Waiting for payment',
OrderStatus::Paid, OrderStatus::Shipped => 'On its way',
};The comparison is ===, each arm is an expression that becomes the result, and a status with no arm throws UnhandledMatchError right where the gap is. A default arm is allowed when a fallback really is the intent.
match (true) with conditions as arms replaces an if/elseif ladder that only picks a value.