← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 15 of 24

PHP Match Expression Advanced

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
<?php
$grade = 85;
$letter = match(true) {
    $grade >= 90 => 'A',
    $grade >= 80 => 'B',
    default => 'C',
};
echo $letter;
?>

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
<?php
$day = 6;
$type = match($day) {
    1, 2, 3, 4, 5 => 'Weekday',
    6, 7 => 'Weekend',
};
echo $type;
?>

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

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

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
<?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 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.