PHP 8 match Expression
The match expression is a cleaner, stricter alternative to switch. It uses strict comparison (===), returns a value, and requires exhaustive handling — eliminating an entire class of switch-related bugs.
<?php
// switch: loose comparison, needs break, no return value
$status = '1'; // a string
switch ($status) {
case 1: echo "Active"; break; // matches '1' too! loose ==
case 0: echo "Inactive"; break;
}
// match: strict comparison, no break, returns value
$label = match($status) {
1 => 'Active', // does NOT match '1' (strict ===)
0 => 'Inactive',
default => 'Unknown',
};
echo $label; // 'Unknown' — '1' !== 1
// Throwing exceptions
$role = 'super';
$level = match($role) {
'superadmin' => 5,
'admin' => 4,
'editor' => 3,
'member' => 1,
default => throw new InvalidArgumentException("Unknown role: $role"),
};
Multiple Conditions Per Arm
<?php
$code = 404;
$type = match(true) {
$code >= 500 => 'Server Error',
$code >= 400 => 'Client Error',
$code >= 300 => 'Redirect',
$code >= 200 => 'Success',
default => 'Unknown',
};
// 'Client Error'
// Multiple values per arm
$day = 'Saturday';
$type = match($day) {
'Monday','Tuesday','Wednesday','Thursday','Friday' => 'Weekday',
'Saturday','Sunday' => 'Weekend',
};
// Use as statement (expression)
echo match($httpCode) {
200 => 'OK', 201 => 'Created', 204 => 'No Content',
400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden',
404 => 'Not Found', 500 => 'Internal Server Error',
default => 'Unknown Status',
};
Q: What happens if no arm matches in a match expression with no default?
PHP throws an UnhandledMatchError — unlike switch which silently falls through. This is actually a safety feature: match forces you to handle all cases explicitly or acknowledge the default. Always add a default arm unless you intentionally want an error for unhandled values.
Comments (0)
No comments yet. Be the first!
Leave a Comment