match Expression

A modern, safer alternative to switch that returns a value.

Syntax$result = match($value) { A, B => "...", default => "..." };

Introduced in PHP 8, the match expression compares a value using strict === comparison and returns a result.

Advantages over switch

  • No break statements needed.
  • Uses strict comparison, avoiding type surprises.
  • It is an expression, so it can be assigned to a variable.

Example

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

When to use it

  • Map HTTP status codes to readable labels using match without risk of accidental fall-through.
  • Select a template file path based on a content type enum value in a rendering engine.
  • Throw an exception for unrecognised operator symbols in a simple expression parser.

More examples

match returns a value

match is an expression that returns a value; multiple comma-separated arms share a result without fall-through.

Example · php
<?php
$status = 404;

$label = match($status) {
    200     => 'OK',
    301, 302 => 'Redirect',
    404     => 'Not Found',
    500     => 'Server Error',
    default => 'Unknown',
};

echo $label; // Not Found

Strict comparison in match

match uses === internally, preventing the loose-equality surprises that switch produces with falsy values.

Example · php
<?php
$input = '0';

// switch: '0' == false is true, so 'No' would print
// match: '0' === false is false, correct arm runs
$result = match($input) {
    false => 'No',
    '0'   => 'Zero string',
    default => 'Other',
};

echo $result; // Zero string

match with no-match exception

A match without a default arm throws UnhandledMatchError for unrecognised values, making missing cases explicit.

Example · php
<?php
function parseOp(string $op): string {
    return match($op) {
        '+' => 'add',
        '-' => 'subtract',
        '*' => 'multiply',
        '/' => 'divide',
    };
    // Throws UnhandledMatchError if $op not listed
}

try {
    echo parseOp('%');
} catch (\UnhandledMatchError $e) {
    echo 'Unknown operator';
}

Discussion

  • Be the first to comment on this lesson.