← Back to PHP Course | Chapter 4: Control Flow | Lesson 8 of 14

PHP match Expression

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
<?php
$status = 2;
$label = match($status) {
    1 => 'Pending',
    2 => 'Active',
    3 => 'Closed',
};
echo $label;
?>

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
<?php
$quantity = 2;
$level = match($quantity) {
    1, 2, 3 => 'low',
    4, 5, 6 => 'medium',
};
echo $level;
?>

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
<?php
$value = '0';
$result = match(true) {
    $value === 0 => 'integer zero',
    $value === '0' => 'string zero',
    default => 'other',
};
echo $result;
?>

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
<?php
$code = 99;
try {
    echo match($code) {
        1 => 'One',
        2 => 'Two',
    };
} catch (\UnhandledMatchError $e) {
    echo "No arm matched: " . $e->getMessage();
}
?>

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
<?php
$age = 25;
$category = match(true) {
    $age < 13 => 'child',
    $age < 20 => 'teen',
    default => 'adult',
};
echo $category;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.