patternphplaravelTip
PHP 8.0 Match Expression vs Switch: Strict Comparison and Exhaustiveness
Viewed 0 times
PHP 8.0+
matchswitchstrict comparisonphp 8.0UnhandledMatchErrorexpressiontype juggling
Error Messages
Problem
switch uses loose comparison (==), falls through by default, requires break statements, and cannot be used as an expression. This causes subtle bugs with type-juggling and bloated code.
Solution
Replace switch with match for value-to-expression mappings. match uses strict comparison (===), does not fall through, throws UnhandledMatchError for unmatched values (forcing exhaustive handling), and is an expression that returns a value.
Why
match's strict comparison avoids PHP type juggling pitfalls. The UnhandledMatchError on unmatched input is a safety net that makes missing cases visible immediately. Being an expression allows assignment and concise code.
Gotchas
- match throws UnhandledMatchError if no arm matches and there is no default—this is intentional but can be a runtime surprise
- Multiple conditions in one arm use comma separation: 1, 2 => 'low'
- match arms must be an expression, not a statement block—use closures or extract to a method for complex logic
- match does not support fall-through—each arm is independent
Code Snippets
match vs switch
// Old switch (loose comparison, fall-through risk)
switch ($status) {
case 'active':
$label = 'Active';
break;
case 'inactive':
$label = 'Inactive';
break;
default:
$label = 'Unknown';
}
// New match (strict, expression)
$label = match($status) {
'active' => 'Active',
'inactive', 'banned'=> 'Inactive',
default => 'Unknown',
};Revisions (0)
No revisions yet.