PHP match expressions

guttume • July 13, 2021

PHP 8 introduced match expressions in addition to switch statements. In this article, we will see how a match expression in PHP differs from a PHP switch statement. First, let us see how a match expression in PHP looks like.

<?php

    $x = 1;

    echo match ($x) {
      1 => "one",
      2 => "two",
      3 => "three",
      4 => "four",
      5 => "five",
      default => "something else",
    };

    // outputs: one

A match expression has a subject expression, result of which is compared to multiple conditions based on which the suitable expression is returned. The conditional expression and the corresponding result expression is separated by the fat arrow symbol (=>).

There can be multiple conditional expression with their corresponding result expression. Each combination is known as match arms and they are separated by comma.

The final match arm must be a default pattern which will match anything that has not matched previously. Multiple default patterns will raise a E_FATAL_ERROR error.

The match expression must be terminated by semicolon.

Though it is not necessary to use the result of a match expression, you will always use it.

Unlike a switch statement, the comparison of the value of subject expression and the conditional expression is an identity check (===) rather than a weak check (==), which means 1 will not be equal to '1'.

Implementing logical OR in a match expression

If we want to compare a conditional expression with multiple values and wants to execute same piece of code for each of them, we can do that in a match expression by using multiple expressions separated by comma in a single match arm.

Example

<?php

$integer = 1;

echo match ($integer) {
  1, 3, 5 => "Odd number",
  2, 4, 6 => "Even number",
  default => "Out of range"
};

// outputs: Odd number

Handling non-identity conditional cases

It is possible to use a match expression to handle non-identity conditional cases by using true as the subject expression.

Example

<?php

    $age = 42;

    echo match (true) {
        $age <= 13 => 'Kid',
        $age <= 18 => 'Teen',
        $age <= 30 => 'Adult',
        $age <= 45 => 'Senior'
        default => 'Old'
    };

    // outputs: Senior

Differences between Match expression and Switch statement in PHP