TExcelTAD
Home › PHP › PHP match

PHP match

PHP 8.0 introduced match, a modern alternative to switch. It is an expression, which means it produces a value you can assign, return or echo. It also compares strictly and never falls through, which removes the two most common switch bugs.

Basic syntax

php
$result = match ($value) {
    pattern1 => expression1,
    pattern2, pattern3 => expression2,
    default => fallback,
};

Each arm has one or more conditions on the left of => and a single expression on the right. Note the trailing semicolon after the closing brace — the whole thing is an expression statement.

php · try it yourself
<?php
$status = 404;

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

echo "$status: $message\n";
404: Not Found

match vs switch

switch match
Kind statement expression (returns a value)
Comparison loose == strict ===
Fall-through yes, needs break never
Multiple values per branch stacked case labels comma-separated
Body any number of statements one expression
No matching branch nothing happens throws UnhandledMatchError

Strict comparison

Because match uses ===, a string never matches an integer arm. This is usually what you want with data from forms or URLs, which always arrives as strings:

php · try it yourself
<?php
function describe(mixed $v): string {
    return match ($v) {
        1 => "the integer one",
        "1" => "the string one",
        true => "boolean true",
        default => "something else",
    };
}

echo describe(1), "\n";
echo describe("1"), "\n";
echo describe(true), "\n";
echo describe(1.0), "\n";
the integer one
the string one
boolean true
something else

With switch, all four calls would have hit the first case.

UnhandledMatchError

If no arm matches and there is no default, match throws an UnhandledMatchError. That is a feature: a silently ignored value is often a bug, and the exception points straight at it. You can catch it like any other exception:

php · try it yourself
<?php
function sizeLabel(string $code): string {
    return match ($code) {
        "S" => "Small",
        "M" => "Medium",
        "L" => "Large",
    };
}

foreach (["M", "XL"] as $code) {
    try {
        echo $code, " -> ", sizeLabel($code), "\n";
    } catch (\UnhandledMatchError $e) {
        echo "Error: ", $e->getMessage(), "\n";
    }
}
M -> Medium
XL -> Error: Unhandled match case 'XL'

Notice that XL -> was already printed before the exception happened: echo with commas outputs each argument in turn.

match (true) for ranges

match arms compare against values, so to test ranges you match against true and write conditions on the left. The first arm whose condition is true wins:

php · try it yourself
<?php
function bmiCategory(float $bmi): string {
    return match (true) {
        $bmi < 18.5 => "underweight",
        $bmi < 25.0 => "healthy",
        $bmi < 30.0 => "overweight",
        default => "obese",
    };
}

foreach ([17.2, 22.0, 27.9, 33.1] as $bmi) {
    printf("%.1f is %s\n", $bmi, bmiCategory($bmi));
}
17.2 is underweight
22.0 is healthy
27.9 is overweight
33.1 is obese

Arms can call functions or throw

The right-hand side can be any expression, including a function call or (since PHP 8.0) a throw expression:

php
$price = match ($plan) {
    "free" => 0,
    "pro" => calculateProPrice($seats),
    default => throw new InvalidArgumentException("Unknown plan: $plan"),
};

Tip: Reach for match whenever a branch just produces a value. Use switch or if when each branch needs several statements.

Test yourself

What does match do when no arm matches and there is no default?

  1. Returns null
  2. Returns false
  3. Throws UnhandledMatchError
  4. Runs the first arm

What is printed by echo match("5") { 5 => 'int', default => 'other' };?

  1. int
  2. other
  3. Nothing
  4. An error

How do you let one match arm handle several values?

  1. Stack multiple case labels
  2. Separate the values with commas
  3. Use || between values
  4. Omit break