ZetCode

PHP match

last modified November 14, 2026

In this article, we show how to do flow control in PHP with the match expression. The expression was introduced in PHP 8.0.

A match expression is a control flow construct in which a subject value is compared against multiple alternatives. It is similar to the switch statement, but it is more compact and safer.

In if/else or switch statements, each individual alternative is called a branch; in a match expression, the term arm is used instead.

Main features of match

The following list summarizes how match differs from switch.

Each arm is a single expression; if we need several statements, we put them into a function or a closure. The trailing comma after the last arm is allowed.

PHP match integer literals

In the first example, we match against integer literals.

menu.php
<?php

declare(strict_types=1);

$menu = <<<MENU
Select option
1 - start
2 - slow down
3 - accelerate
4 - pause
5 - terminate
MENU;

echo $menu, "\n";

$opt = (int) trim(fgets(STDIN));

$res = match ($opt) {
    1 => 'start',
    2 => 'slow down',
    3 => 'accelerate',
    4 => 'pause',
    5 => 'terminate',
    default => 'unknown',
};

echo "your option: $res\n";

We have a menu of options; each option is represented by an integer.

$opt = (int) trim(fgets(STDIN));

We read a line from the standard input, remove the trailing newline with trim and convert the text to an integer. Since a match arm compares strictly, the conversion is necessary; the string '3' would not match the integer 3.

$res = match ($opt) {
    1 => 'start',
    2 => 'slow down',
    ...
    default => 'unknown',
};

The match expression compares the selected option against a list of values. Each arm consists of a condition, the => operator, and a result expression, and the arms are separated by commas. For all other values, we have the default arm.

We run the program twice with the input piped from the echo command. The second run shows the default arm.

$ echo 3 | php menu.php
Select option
1 - start
2 - slow down
3 - accelerate
4 - pause
5 - terminate
your option: accelerate
$ echo 9 | php menu.php
your option: unknown

PHP match string literals

In the second example, we match against string literals.

greetings.php
<?php

declare(strict_types=1);

$langs = ['russian', 'slovak', 'german', 'swedish',
    'hungarian', 'french', 'spanish'];

echo "say hello\n";

foreach ($langs as $lang) {

    $res = match ($lang) {
        'russian' => 'привет',
        'hungarian' => 'szia',
        'french' => 'salut',
        'spanish' => 'hola',
        'slovak' => 'ahoj',
        'german' => 'hallo',
        'swedish' => 'hallå',
    };

    echo "$lang: $res\n";
}

We have a list of languages. We go through the list and say hello for each language. Every language in the list has its own arm, so we do not need a default arm.

$ php greetings.php
say hello
russian: привет
slovak: ahoj
german: hallo
swedish: hallå
hungarian: szia
french: salut
spanish: hola

PHP match multiple options

Multiple conditions in one arm are separated with a comma. The arm matches if any of the conditions matches.

grades.php
<?php

declare(strict_types=1);

$grades = ['A', 'B', 'C', 'D', 'E', 'F', 'FX'];

foreach ($grades as $grade) {

    $res = match ($grade) {
        'A', 'B', 'C', 'D', 'E' => 'passed',
        'F', 'FX' => 'failed',
    };

    echo "$grade: $res\n";
}

We have a list of grades. For the grades A through E, the student passes the exam. For the grades F and FX, the student fails.

$ php grades.php
A: passed
B: passed
C: passed
D: passed
E: passed
F: failed
FX: failed

PHP match conditional arms

A match expression can be used instead of an if/elseif chain. We pass true as the subject, and each arm contains a condition. The first arm whose condition evaluates to true wins, because true === true.

conditions.php
<?php

declare(strict_types=1);

$values = [-5, 0, 3];

foreach ($values as $r) {

    $res = match (true) {
        $r < 0 => "$r: negative value",
        $r === 0 => "$r: zero",
        $r > 0 => "$r: positive value",
    };

    echo "$res\n";
}

The example determines whether an integer is negative, zero, or positive. We use a fixed list of values to get reproducible output.

$r < 0 => "$r: negative value",

This arm is executed if $r is less than zero. The arms are evaluated from top to bottom and the evaluation stops at the first match, so more specific conditions must come before general ones.

$ php conditions.php
-5: negative value
0: zero
3: positive value

PHP match inspects types

The match (true) idiom works with any boolean expression, such as type checks, instanceof, or string functions.

types.php
<?php

declare(strict_types=1);

function describe(mixed $value): string
{
    return match (true) {
        is_int($value) && $value < 0 => 'negative integer',
        is_int($value) => 'non-negative integer',
        is_float($value) => 'float',
        is_string($value) && str_starts_with($value, 'http') => 'URL string',
        is_string($value) => 'string',
        is_array($value) => 'array with ' . count($value) . ' elements',
        $value instanceof DateTimeInterface => 'date and time',
        default => 'unknown',
    };
}

$values = [
    'minus three' => -3,
    'answer' => 42,
    'pi' => 3.14,
    'url' => 'https://example.com',
    'word' => 'falcon',
    'list' => [1, 2, 3],
    'date' => new DateTimeImmutable('2026-01-15'),
    'nothing' => null,
];

foreach ($values as $name => $value) {
    echo str_pad($name, 12), describe($value), "\n";
}

The describe function returns a description of the type of the given value. The arm order matters: the negative integer test comes before the general integer test, and the URL test comes before the general string test.

$ php types.php
minus three negative integer
answer      non-negative integer
pi          float
url         URL string
word        string
list        array with 3 elements
date        date and time
nothing     unknown

PHP match range checks

Because arms are ordinary expressions, we can test ranges. This is not possible with a plain switch.

http_status.php
<?php

declare(strict_types=1);

$codes = [200, 201, 204, 301, 404, 418, 500];

foreach ($codes as $code) {

    $text = match (true) {
        $code === 418 => "I'm a teapot",
        $code >= 200 && $code < 300 => 'Success',
        $code >= 300 && $code < 400 => 'Redirection',
        $code >= 400 && $code < 500 => 'Client error',
        $code >= 500 => 'Server error',
    };

    echo "$code $text\n";
}

We classify HTTP status codes. The special code 418 is tested first, so it is not swallowed by the more general 4xx arm.

$ php http_status.php
200 Success
201 Success
204 Success
301 Redirection
404 Client error
418 I'm a teapot
500 Server error

PHP match strict comparison

The match expression uses the identity operator. In the following example, we compare it with switch, which compares loosely.

strict.php
<?php

$input = '1';

$a = match ($input) {
    1 => 'integer one',
    '1' => 'string one',
    default => 'something else',
};

echo "match:  $a\n";

switch ($input) {
    case 1:
        $b = 'integer one';
        break;
    case '1':
        $b = 'string one';
        break;
    default:
        $b = 'something else';
}

echo "switch: $b\n";

The subject is the string '1'. The switch statement takes the first case, 1, because '1' == 1 is true. The match expression skips the integer arm and chooses the string arm, because '1' === 1 is false. Strict comparison removes a whole class of type-juggling bugs.

$ php strict.php
match:  string one
switch: integer one

PHP match UnhandledMatchError

If no arm matches and there is no default arm, PHP throws the UnhandledMatchError exception.

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";

try {
    echo colorName(7), "\n";
} catch (UnhandledMatchError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    echo match ('yellow') {
        'red' => 1,
        'green' => 2,
    };
} catch (UnhandledMatchError $e) {
    echo $e->getMessage(), "\n";
}

The colorName function handles only three codes. The call with the code 7 throws the exception, which we catch and print. The exception message only names the type of the unhandled value, not the value itself.

This behaviour is a feature: an unexpected value fails loudly instead of silently producing null, as a switch without a default case would.

$ php unhandled.php
green
UnhandledMatchError: Unhandled match case of type int
Unhandled match case of type string

PHP match with throw

Since PHP 8.0, throw is an expression, so it can be used as the result of an arm. This allows us to raise a meaningful error for invalid input.

throw_arm.php
<?php

declare(strict_types=1);

function toBytes(string $unit, int $n): int
{
    return $n * match (strtoupper($unit)) {
        'B' => 1,
        'KB' => 1024,
        'MB' => 1024 ** 2,
        'GB' => 1024 ** 3,
        default => throw new InvalidArgumentException("Unknown unit: $unit"),
    };
}

echo toBytes('kb', 4), "\n";
echo toBytes('MB', 2), "\n";

try {
    echo toBytes('XB', 1), "\n";
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

The toBytes function multiplies a number by the size of a unit. The match expression is used directly as an operand of the multiplication. The default arm throws an InvalidArgumentException instead of returning a value.

$ php throw_arm.php
4096
2097152
Unknown unit: XB

PHP match evaluates arms lazily

The conditions of the arms are evaluated from top to bottom until one of them matches. The remaining conditions and all result expressions of the other arms are never evaluated.

lazy.php
<?php

declare(strict_types=1);

function check(string $name): string
{
    echo "evaluating $name\n";

    return $name;
}

$res = match ('b') {
    check('a') => 'first arm',
    check('b') => 'second arm',
    check('c') => 'third arm',
    default => 'default arm',
};

echo "result: $res\n";

Each arm condition is a call to the check function, which prints a message. The function is called for the arms a and b. The arm c is never evaluated, because the second arm has already matched.

$ php lazy.php
evaluating a
evaluating b
result: second arm

PHP match with enums

The match expression works well with enums, whose cases are compared by identity.

enum.php
<?php

declare(strict_types=1);

enum Status
{
    case Draft;
    case Published;
    case Archived;
}

function label(Status $status): string
{
    return match ($status) {
        Status::Draft => 'Waiting for review',
        Status::Published => 'Visible to everyone',
        Status::Archived => 'Hidden',
    };
}

foreach (Status::cases() as $status) {
    echo str_pad($status->name, 10), label($status), "\n";
}

We map each case of the Status enum to a label. We do not need the default arm, because all cases are covered. If we add a new case to the enum and forget to update the match expression, PHP throws UnhandledMatchError at runtime, and static analysis tools such as PHPStan report the missing arm.

$ php enum.php
Draft     Waiting for review
Published Visible to everyone
Archived  Hidden

Source

PHP manual: match

PHP manual: UnhandledMatchError

RFC: Match expression v2

In this article, we have worked with the PHP match expression. We have matched integers, strings, enums and conditions, and we have used UnhandledMatchError and throw. See also the PHP flow control, switch and enum 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.