match vs switch

Both branch on a value, but match is an expression, uses strict ===, needs no break, and errors loudly on no match.

Reach for match first; keep switch for the rare case you genuinely want fall-through or to run several statements per branch. Here's why match usually wins:

matchswitch
Returns a valueyesno
Comparisonstrict ===loose ==
Fall-throughneverunless you break
No matchthrows UnhandledMatchErrorsilently does nothing

Easy example

<?php
$code = 2;
$label = match($code) {
    1, 2, 3 => 'low',
    4, 5    => 'high',
    default => 'unknown',
};
echo $label; // low

That UnhandledMatchError is a feature: it turns a forgotten case into a loud failure instead of a silent bug.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Replace a switch block in a status renderer with match to guarantee strict type comparison on integer codes.
  • Use match as an expression inside a return statement to avoid verbose temporary variables.
  • Catch missing cases early in a command-line dispatcher by letting match throw UnhandledMatchError.

More examples

switch vs match side by side

match's strict === avoids the falsy/loose traps of switch, catching type mismatches that switch would silently accept.

Example · php
<?php
$status = '1'; // string from form

// switch uses loose ==
switch ($status) {
    case 1: echo 'Active'; break;  // prints! '1' == 1
}

// match uses strict ===
$label = match($status) {
    1       => 'Active',
    default => 'Other',  // hits here: '1' !== 1
};
echo $label; // Other

match as an expression

match(true) evaluates each arm as a condition expression, making it a clean alternative to if/elseif chains.

Example · php
<?php
function httpLabel(int $code): string {
    return match(true) {
        $code >= 500 => 'Server Error',
        $code >= 400 => 'Client Error',
        $code >= 300 => 'Redirect',
        $code >= 200 => 'Success',
        default      => 'Informational',
    };
}

echo httpLabel(404); // Client Error
echo httpLabel(200); // Success

UnhandledMatchError on no match

Omitting default makes unrecognised values fail loudly with UnhandledMatchError, surfacing missing cases during development.

Example · php
<?php
function getIcon(string $ext): string {
    return match($ext) {
        'pdf'       => 'icon-pdf',
        'jpg','png' => 'icon-image',
        'mp4'       => 'icon-video',
        // No default: unknown extensions throw
    };
}

try {
    echo getIcon('exe');
} catch (\UnhandledMatchError) {
    echo 'Unsupported file type';
}

Discussion

  • Be the first to comment on this lesson.