How to use Match in PHP 8

In PHP 8, the match expression was introduced as a more concise and powerful alternative to the switch statement. The match expression allows you to perform pattern matching against a value and execute code based on the matched pattern.

Here’s the basic syntax of the match expression:

match ($value) {
    pattern_1 => expression_1,
    pattern_2 => expression_2,
    // more patterns and expressions...
    pattern_n => expression_n,
    default => expression_default
};

Here’s how it works:

  • The $value is the expression that you want to match against.
  • pattern_1, pattern_2, and pattern_n are the patterns you want to match against the value. These can be literal values, constants, or expressions.
  • expression_1, expression_2, and expression_n are the expressions that will be executed if the corresponding pattern matches.
  • default is an optional keyword that specifies the default case when none of the patterns match. expression_default is the expression executed in the default case.

The match expression evaluates the value and compares it against each pattern in order. If a pattern matches, the corresponding expression is executed, and the match expression completes. If none of the patterns match, the default case (if provided) is executed. If no default case is provided and no pattern matches, a MatchError is thrown.

Here’s an example to illustrate the usage of the match expression:

$result = match ($value) {
    0 => 'Zero',
    1 => 'One',
    2, 3 => 'Two or Three',
    4, 5, 6 => 'Four, Five, or Six',
    default => 'Other'
};

In this example, the value of $value is matched against different patterns, and the corresponding expressions are executed based on the match. The result is assigned to the variable $result.

The match expression in PHP 8 provides a more expressive and concise way to perform pattern matching, making your code easier to read and maintain.