PHP Match Expression (match)
PHP Match Expression (match)
The PHP match expression is a powerful feature introduced in PHP 8.0 that provides a more concise and flexible alternative to switch statements.
Basic Match Syntax
$result = match ($value) {
pattern1 => expression1,
pattern2 => expression2,
// ...
default => default_expression,
};
Comparison switch vs match
// switch statement
switch ($statusCode) {
case 200:
$message = 'OK';
break;
case 404:
$message = 'Not Found';
break;
case 500:
$message = 'Server Error';
break;
default:
$message = 'Unknown';
}
// match equivalent
$message = match ($statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
Various Usage Examples:
// multiple conditions
$result = match ($httpCode) {
200, 201, 202 => 'Success',
400, 401, 403 => 'Client Error',
500, 501, 502 => 'Server Error',
default => 'Unknown',
};
// Match uses strict comparison (===)
$result = match ($value) {
0 => 'Integer zero',
'0' => 'String zero',
false => 'Boolean false',
default => 'Other',
};
// Complex Expressions
$age = 25;
$category = match (true) {
$age < 13 => 'Child',
$age < 20 => 'Teenager',
$age < 65 => 'Adult',
default => 'Senior',
};
// returning different types
function processValue($value) {
return match ($value) {
'int' => 42,
'string' => 'Hello World',
'array' => [1, 2, 3],
'bool' => true,
default => null,
};
}
// Using with arrays
$user = [
'role' => 'admin',
'status' => 'active'
];
$permissions = match ($user['role']) {
'admin' => ['read', 'write', 'delete'],
'editor' => ['read', 'write'],
'viewer' => ['read'],
default => [],
};
// nested match expressions
$result = match ($type) {
'number' => match ($value) {
$value > 0 => 'Positive',
$value < 0 => 'Negative',
default => 'Zero',
},
'string' => 'String type',
default => 'Unknown type',
};
// Conditional Logic in Patterns
$score = 85;
$grade = match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
$score >= 70 => 'C',
$score >= 60 => 'D',
default => 'F',
};
Advantages Over Switch
- Returns a value - Can be assigned directly to variables
- No fall-through - Prevents accidental bugs
- Strict comparisons - More predictable behavior
- More concise - Less boilerplate code
- Better error handling - Throws UnhandledMatchError for unhandled cases
Important Notes
- Match expressions must be exhaustive or include a default case
- Throws UnhandledMatchError if no pattern matches and no default is provided
- Each arm must be a single expression (use anonymous functions for complex logic)
- Patterns are evaluated in order, first match wins
The match expression is a significant improvement that makes conditional logic more readable, safer, and more expressive in modern PHP code.