ZetCode

PHP match Expression

last modified November 25, 2026

The PHP match expression, introduced in PHP 8.0, compares a value against several alternatives and returns the result of the first matching arm. It is similar to switch, but it is an expression, compares strictly, and does not fall through.

This article explains the syntax and the behaviour of the keyword. The PHP match tutorial covers the same feature with more extended examples.

Basic definitions

The match expression, introduced in PHP 8.0, compares a subject against a list of arms and returns the result of the first arm that matches. Each arm consists of one or more conditions, the => operator, and a result expression.

A match expression has the following properties.

The syntax is match (subject) { condition => result, ... }. A trailing comma after the last arm is allowed. Every arm is a single expression; when several statements are needed, put them in a function and call it from the arm.

A first match expression

The first example maps an HTTP status code to a message. The result is stored in a variable.

status.php
<?php

declare(strict_types=1);

$code = 404;

$message = match ($code) {
    200 => 'OK',
    301 => 'Moved Permanently',
    404 => 'Not Found',
    500 => 'Internal Server Error',
    default => 'Unknown Status Code',
};

echo "$code: $message\n";

The subject is compared with each arm from top to bottom. The code 404 matches the third arm, so the expression evaluates to Not Found. The default arm handles every value that is not listed; without it, an unknown code would throw an UnhandledMatchError.

$ php status.php
404: Not Found

Several values in one arm

Conditions that should produce the same result can be combined in one arm. This replaces the repeated case labels and break statements of a switch.

arms.php
<?php

declare(strict_types=1);

function dayType(int $day): string
{
    return match ($day) {
        1, 2, 3, 4, 5 => 'weekday',
        6, 7 => 'weekend',
        default => 'invalid day',
    };
}

foreach ([1, 6, 9] as $day) {
    echo "$day: ", dayType($day), "\n";
}

The arm 1, 2, 3, 4, 5 matches any of the five weekdays, and 6, 7 matches the weekend. The value 9 reaches default. Conditions in one arm are alternatives, not a range: to match a range, use match (true) with comparison expressions.

$ php arms.php
1: weekday
6: weekend
9: invalid day

Conditional arms

When the decision depends on ranges or several variables, use true as the subject and put boolean expressions in the arms. The first expression that evaluates to true wins.

conditions.php
<?php

declare(strict_types=1);

$age = 25;
$score = 87;

$category = match (true) {
    $age < 13 => 'child',
    $age < 20 => 'teenager',
    $age < 65 => 'adult',
    default => 'senior',
};

$grade = match (true) {
    $score >= 90 => 'A',
    $score >= 80 => 'B',
    $score >= 70 => 'C',
    default => 'D',
};

echo "category: $category\n";
echo "grade:    $grade\n";

Order matters: if the $age < 65 arm were first, every younger person would also match it. The same technique produces a grade from a score. Keep the conditions mutually exclusive or order them from most specific to most general.

$ php conditions.php
category: adult
grade:    B

Strict comparison

The most important difference from switch is the comparison operator. match uses ===, so the string "1" does not match the integer 1.

strict.php
<?php

declare(strict_types=1);

$value = '1';

switch ($value) {
    case 1:
        $switchResult = 'integer';
        break;
    case '1':
        $switchResult = 'string';
        break;
    default:
        $switchResult = 'other';
}

$matchResult = match ($value) {
    1 => 'integer',
    '1' => 'string',
    default => 'other',
};

echo "switch: $switchResult\n";
echo "match:  $matchResult\n";

The switch reaches case 1 first because "1" == 1 is true in PHP's loose comparison. The match skips the integer arm and selects the string arm. If the value comes from a form or a database, cast or validate it before matching so that the arm types are predictable.

$ php strict.php
switch: integer
match:  string

When no arm matches

A match expression does not silently return null. If no arm matches and there is no default, PHP throws an UnhandledMatchError. This is a runtime check, not a compile-time proof of exhaustiveness.

unhandled.php
<?php

declare(strict_types=1);

function colorName(int $code): string
{
    return match ($code) {
        1 => 'red',
        2 => 'green',
        3 => 'blue',
    };
}

echo colorName(2), "\n";
echo colorName(7), "\n";

The first call returns green. The second call receives 7, finds no matching arm, and terminates the script with the error shown above. The message includes the unhandled integer; for some other types it names only the type. Catching the error is covered in the PHP exceptions tutorial; the full treatment of match is in the PHP match article.

$ php unhandled.php
green

Fatal error: Uncaught UnhandledMatchError: Unhandled match case 7 in /app/unhandled.php:7
Stack trace:
#0 /app/unhandled.php(15): colorName(7)
#1 {main}
  thrown in /app/unhandled.php on line 7

Matching enum cases

Match expressions work well with enums. Listing every case documents the mapping and fails loudly if a new case is added without updating the expression.

enum.php
<?php

declare(strict_types=1);

enum Role: string
{
    case ADMIN = 'admin';
    case EDITOR = 'editor';
    case READER = 'reader';
}

function permissions(Role $role): array
{
    return match ($role) {
        Role::ADMIN => ['create', 'read', 'update', 'delete'],
        Role::EDITOR => ['create', 'read', 'update'],
        Role::READER => ['read'],
    };
}

foreach (Role::cases() as $role) {
    echo $role->value, ": ", implode(', ', permissions($role)), "\n";
}

The function accepts a Role and returns an array of permissions. All three cases are covered here, so no default arm is needed. This is still a runtime mapping: adding a fourth case would make an unmatched call fail rather than forcing an immediate compile error. Add a default arm when the enum is maintained by another package or when a fallback is acceptable.

$ php enum.php
admin: create, read, update, delete
editor: create, read, update
reader: read

Match is an expression

A match expression produces a value and evaluates only the selected arm. Side effects in the other arms do not run.

lazy.php
<?php

declare(strict_types=1);

function evaluate(string $name): string
{
    echo "evaluating $name\n";
    return strtoupper($name);
}

$result = match (2) {
    1 => evaluate('one'),
    2 => evaluate('two'),
    3 => evaluate('three'),
};

echo "result: $result\n";

Only the arm for 2 is evaluated, so only evaluating two is printed. The result is then uppercased and printed. This lazy behaviour makes match suitable for choosing between expensive operations: the result expressions of the other arms never run.

$ php lazy.php
evaluating two
result: TWO

What match is not

Despite the name, match is not a general pattern-matching construct. It has no array destructuring, no guards, and no type patterns. An arm is simply a value or expression compared with the subject using ===.

For structural conditions, use match (true) with explicit checks such as isset, instanceof, or comparisons. For several statements per branch, call a function. This keeps the arms readable and preserves the expression's single-value nature.

Best practices

Use match for short value mappings and for conditions that fit naturally into a single expression.

Source

PHP manual: match PHP manual: UnhandledMatchError RFC: match expression v2 PHP manual: switch

In this article we have used the PHP match expression with integer and string subjects, multiple conditions per arm, conditional arms, enums, and a missing arm. We have also seen that only the selected arm is evaluated. See also the switch statement, enum, and conditionals tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.