PHP Match Expression Advanced
In this page:
$result = match(true) {
condition1 => result1,
condition2, condition3 => result2,
default => default_result,
};
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
// Declare `$grade`, set to `85`
$grade = 85;
$letter = match(true) {
$grade >= 90 => 'A',
$grade >= 80 => 'B',
default => 'C',
};
// Print `$letter` to the output
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
// Declare `$day`, set to `6`
$day = 6;
$type = match($day) {
1, 2, 3, 4, 5 => 'Weekday',
6, 7 => 'Weekend',
};
// Print `$type` to the output
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
// Declare `$value`, set to '1'
$value = '1';
$result = match(true) {
$value === 1 => 'integer one',
$value === '1' => 'string one',
};
// Print `$result` to the output
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
// Declare `$code`, set to `99`
$code = 99;
// Try running this block; jump to `catch` if it throws
try {
// Print `match($code) {` to the output
echo match($code) {
1 => 'One',
};
// Catch \UnhandledMatchError $e
} catch (\UnhandledMatchError $e) {
// Print `"Unhandled: " . $e->getMessage()` to the output
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
// Define the function `checkStatus` taking `$status`
function checkStatus($status) {
// Return `match($status) {` from this function
return match($status) {
'active', 'pending' => true,
default => throw new InvalidArgumentException("Invalid status: $status"),
};
}
// Try running this block; jump to `catch` if it throws
try {
// Call `checkStatus('deleted')`
checkStatus('deleted');
// Catch InvalidArgumentException $e
} catch (InvalidArgumentException $e) {
// Print `$e->getMessage()` to the output
echo $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
- Expecting
matchto fall through likeswitch, when each arm returns and stops. - Not adding a
defaultarm and getting anUnhandledMatchErrorfor values that match nothing. - Forgetting that
matchuses strict comparison, so"1"does not match1.
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