PHP Match Expression Advanced
In this page:
What is the match Expression?
match is a stricter, more concise alternative to switch: it's an expression that returns a value directly, requires no break statements, and can't accidentally fall through to the next case.
Example: What is the match Expression?
<?php
$grade = 85;
$letter = match(true) {
$grade >= 90 => 'A',
$grade >= 80 => 'B',
default => 'C',
};
echo $letter;
?>
Login to try C/C++/Java/PHP code in the editor
Multiple Matches
You can list several comma-separated values on one match arm to share a single result, which avoids the repetition switch would otherwise require for each fall-through case.
Example: Multiple Matches
<?php
$day = 6;
$type = match($day) {
1, 2, 3, 4, 5 => 'Weekday',
6, 7 => 'Weekend',
};
echo $type;
?>
Login to try C/C++/Java/PHP code in the editor
Strict Type Matching
Unlike switch's loose == comparison, match compares with strict === semantics, checking type as well as value -- so match(true) and matching 1 against 1 behave very differently than in a switch statement.
Example: Strict Type Matching
<?php
$value = '1';
$result = match(true) {
$value === 1 => 'integer one',
$value === '1' => 'string one',
};
echo $result;
?>
Login to try C/C++/Java/PHP code in the editor
The default Match Fallback
Omitting a default arm means match throws an UnhandledMatchError the moment no arm's value matches the subject, which surfaces unexpected inputs immediately instead of silently doing nothing like an unmatched switch would.
Example: The default Match Fallback
<?php
$code = 99;
try {
echo match($code) {
1 => 'One',
};
} catch (\UnhandledMatchError $e) {
echo "Unhandled: " . $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
Throwing Exceptions inside match
Because match is an expression, you can put a throw statement directly inside an arm to reject an invalid case right where it's detected, keeping validation logic compact and colocated with the other arms.
Example: Throwing Exceptions inside match
<?php
function checkStatus($status) {
return match($status) {
'active', 'pending' => true,
default => throw new InvalidArgumentException("Invalid status: $status"),
};
}
try {
checkStatus('deleted');
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser