PHP match Expression
In this page:
Basic match Expression
match, added in PHP 8.0, compares a value against a set of arms and *returns* the result of whichever one matches — you assign it directly ($label = match($status) {...}) rather than writing separate echo/assignment statements inside each branch, the way switch requires.
Example: Basic match Expression
<?php
$status = 2;
$label = match($status) {
1 => 'Pending',
2 => 'Active',
3 => 'Closed',
};
echo $label;
?>
Login to try C/C++/Java/PHP code in the editor
Grouping values with Comma
A single match arm can test for several values at once by listing them comma-separated before the => — 1, 2, 3 => low runs the same result for any of those three values, without needing three separate arms.
Example: Grouping values with Comma
<?php
$quantity = 2;
$level = match($quantity) {
1, 2, 3 => 'low',
4, 5, 6 => 'medium',
};
echo $level;
?>
Login to try C/C++/Java/PHP code in the editor
Strict Type Comparison
switch uses loose comparison (==), so 0 == 0 can match unexpectedly. match always compares with strict semantics (===), so a string 1 will never accidentally match an integer 1 — this closes off a whole category of subtle bugs that switch is prone to.
Example: Strict Type Comparison
<?php
$value = '0';
$result = match(true) {
$value === 0 => 'integer zero',
$value === '0' => 'string zero',
default => 'other',
};
echo $result;
?>
Login to try C/C++/Java/PHP code in the editor
The default Fallback Case
match requires every possible input to be handled — if a value hits no arm and there's no default, PHP throws an UnhandledMatchError instead of silently doing nothing. That's a deliberate design choice: rather than a case slipping through unnoticed, a missing branch becomes a hard error you can catch immediately.
Example: The default Fallback Case
<?php
$code = 99;
try {
echo match($code) {
1 => 'One',
2 => 'Two',
};
} catch (\UnhandledMatchError $e) {
echo "No arm matched: " . $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
Complex Conditions in match
Passing true as the value being matched, then writing boolean expressions as the arm conditions, lets match evaluate arbitrary comparisons rather than just fixed values — effectively turning it into a strict, expression-based replacement for an elseif ladder.
Example: Complex Conditions in match
<?php
$age = 25;
$category = match(true) {
$age < 13 => 'child',
$age < 20 => 'teen',
default => 'adult',
};
echo $category;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: