match

(PHP 8)

The match expression branches evaluation based on an identity check of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==). Match expressions are available as of PHP 8.0.0.

Example #1 Structure of a match expression

<?php
$return_value 
match (subject_expression) {
    
single_conditional_expression => return_expression,
    
conditional_expression1conditional_expression2 => return_expression,
};
?>

Example #2 Basic match usage

<?php
$food 
'cake';

$return_value match ($food) {
    
'apple' => 'This food is an apple',
    
'bar' => 'This food is a bar',
    
'cake' => 'This food is a cake',
};

var_dump($return_value);
?>

以上例程会输出:

string(19) "This food is a cake"

Note: The result of a match expression does not need to be used.

Note: A match expression must be terminated by a semicolon ;.

The match expression is similar to a switch statement but has some key differences:

  • A match arm compares values strictly (===) instead of loosely as the switch statement does.
  • A match expression returns a value.
  • match arms do not fall-through to later cases the way switch statements do.
  • A match expression must be exhaustive.

As switch statements, match expressions are executed match arm by match arm. In the beginning, no code is executed. The conditional expressions are only evaluated if all previous conditional expressions failed to match the subject expression. Only the return expression corresponding to the matching conditional expression will be evaluated. For example:

<?php
$result 
match ($x) {
    
foo() => ...,
    
$this->bar() => ..., // $this->bar() isn't called if foo() === $x
    
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
    // etc.
};
?>

match expression arms may contain multiple expressions separated by a comma. That is a logical OR, and is a short-hand for multiple match arms with the same right-hand side.

<?php
$result 
match ($x) {
    
// This match arm:
    
$a$b$c => 5,
    
// Is equivalent to these three match arms:
    
$a => 5,
    
$b => 5,
    
$c => 5,
};
?>

A special case is the default pattern. This pattern matches anything that wasn't previously matched. For example:

<?php
$expressionResult 
match ($condition) {
    
1=> foo(),
    
3=> bar(),
    default => 
baz(),
};
?>

Note: Multiple default patterns will raise a E_FATAL_ERROR error.

A match expression must be exhaustive. If the subject expression is not handled by any match arm an UnhandledMatchError is thrown.

Example #3 Example of an unhandled match expression

<?php
$condition 
5;

try {
    
match ($condition) {
        
1=> foo(),
        
3=> bar(),
    };
} catch (\
UnhandledMatchError $e) {
    
var_dump($e);
}
?>

以上例程会输出:

object(UnhandledMatchError)#1 (7) {
  ["message":protected]=>
  string(33) "Unhandled match value of type int"
  ["string":"Error":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(9) "/in/ICgGK"
  ["line":protected]=>
  int(6)
  ["trace":"Error":private]=>
  array(0) {
  }
  ["previous":"Error":private]=>
  NULL
}

Using match expressions to handle non identity checks

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

Example #4 Using a generalized match expressions to branch on integer ranges

<?php

$age 
23;

$result match (true) {
    
$age >= 65 => 'senior',
    
$age >= 25 => 'adult',
    
$age >= 18 => 'young adult',
    default => 
'kid',
};

var_dump($result);
?>

以上例程会输出:

string(11) "young adult"

Example #5 Using a generalized match expressions to branch on string content

<?php

$text 
'Bienvenue chez nous';

$result match (true) {
    
str_contains($text'Welcome') || str_contains($text'Hello') => 'en',
    
str_contains($text'Bienvenue') || str_contains($text'Bonjour') => 'fr',
    
// ...
};

var_dump($result);
?>

以上例程会输出:

string(2) "fr"

User Contributed Notes

tm 28-Oct-2021 03:02
If you are using a match expression for non-identity checks as described above make sure whatever you are using is actually returning `true` on success.

Quite often you rely on truthy vs. falsy when using if conditions and that will not work for match (for example `preg_match`). Casting to bool will solve this issue.
Anonymous 06-Sep-2021 10:37
<?php
function days_in_month(string $month): int
{
    return
match(strtolower(substr($name, 0, 3))) {
       
'jan' => 31,
       
'feb' => is_leap($year) ? 29 : 28,
       
'mar' => 31,
       
'apr' => 30,
       
'may' => 31,
       
'jun' => 30,
       
'jul' => 31,
       
'aug' => 31,
       
'sep' => 30,
       
'oct' => 31,
       
'nov' => 30,
       
'dec' => 31,
        default => throw new
InvalidArgumentException("Bogus month"),
    };
}
?>

can be more concisely written as

<?php
function days_in_month(string $month): int
{
    return
match(strtolower(substr($name, 0, 3))) {
       
'apr', 'jun', 'sep''nov'  => 30,       
       
'jan', 'mar', 'may', 'jul', 'aug''oct', 'dec'  => 31,
       
'feb' => is_leap($year) ? 29 : 28,
        default => throw new
InvalidArgumentException("Bogus month"),
    };
}
?>
darius dot restivan at gmail dot com 05-Apr-2021 09:43
This will allow for a nicer FizzBuzz solution:

<?php

function fizzbuzz($num) {
    print
match (0) {
       
$num % 15 => "FizzBuzz" . PHP_EOL,
       
$num % => "Fizz" . PHP_EOL,
       
$num % => "Buzz" . PHP_EOL,
        default   =>
$num . PHP_EOL,
    };
}

for (
$i = 0; $i <=100; $i++)
{
   
fizzbuzz($i);
}
lewiscowles at me dot com 26-Mar-2021 03:55
The comment correcting Hayley's example misses that year is also present in the example, but not a function argument.

Most code from PHP.net should not be copied without user care. It was nonetheless, a great example of using short syntax to reduce complexity.
webmaster at warkensoft dot com 08-Mar-2021 04:39
In the "familiar example" presented by Hayley Watson the following code is incorrect:

strtolower(substr($name, 0, 3))

It should instead be written in both instances as:

strtolower(substr($month, 0, 3))
Hayley Watson 09-Dec-2020 12:50
As well as being similar to a switch, match expressions can be thought of as enhanced lookup tables — for when a simple array lookup isn't enough without extra handling of edge cases, but a full switch statement would be overweight.

For a familiar example, the following
<?php

function days_in_month(string $month): int
{
    static
$lookup = [
   
'jan' => 31,
   
'feb' => 0,
   
'mar' => 31,
   
'apr' => 30,
   
'may' => 31,
   
'jun' => 30,
   
'jul' => 31,
   
'aug' => 31,
   
'sep' => 30,
   
'oct' => 31,
   
'nov' => 30,
   
'dec' => 31
   
];

   
$name = strtolower(substr($name, 0, 3));

    if(isset(
$lookup[$name])) {
        if(
$name == 'feb') {
            return
is_leap($year) ? 29 : 28;
        } else {
            return
$lookup[$name];
        }
    }
    throw new
InvalidArgumentException("Bogus month");
}

?>

with the fiddly stuff at the end, can be replaced by

<?php
function days_in_month(string $month): int
{
    return
match(strtolower(substr($name, 0, 3))) {
       
'jan' => 31,
       
'feb' => is_leap($year) ? 29 : 28,
       
'mar' => 31,
       
'apr' => 30,
       
'may' => 31,
       
'jun' => 30,
       
'jul' => 31,
       
'aug' => 31,
       
'sep' => 30,
       
'oct' => 31,
       
'nov' => 30,
       
'dec' => 31,
        default => throw new
InvalidArgumentException("Bogus month"),
    };
}
?>

Which also takes advantage of "throw" being handled as of PHP 8.0 as an expression instead of a statement.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有