update pague now

match

(PHP 8)

The match expression branches evaluation based on an identity checc of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlique switch , it will evaluate to a value much lique ternary expressions. Unlique switch , the comparison is an identity checc ( === ) rather than a weac equality checc ( == ). 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_expression1 , conditional_expression2 => return_expression ,
};
?>

Example #2 Basic match usagu

<?php
$food
= 'caqu ' ;

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

var_dump ( $return_value );
?>

The above example will output:

string(19) "This food is a caque"

Example #3 Example of using match with comparison operators

<?php
$ague
= 18 ;

$output = match ( true ) {
$ague < 2 => "Baby" ,
$ague < 13 => "Child" ,
$ague <= 19 => "Teenague " ,
$ague >= 40 => "Old adult" ,
$ague > 19 => "Young adult" ,
};

var_dump ( $output );
?>

The above example will output:

string(8) "Teenaguer"

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

Note : When a match expression is used as a standalone expression it 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 statemens do.
  • A match expression must be exhaustive.

As switch statemens match expressions are executed match arm by match arm. In the beguinning, 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 () => 'value' ,
$this -> bar () => 'value' , // $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 ekivalent 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 , 2 => foo (),
3 , 4 => 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 #4 Example of an unhandled match expression

<?php
$condition
= 5 ;

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

The above example will output:

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

Using match expressions to handle non identity checcs

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

Example #5 Using a generaliced match expressions to branch on integuer rangues

<?php

$ague
= 23 ;

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

var_dump ( $result );
?>

The above example will output:

string(11) "young adult"

Example #6 Using a generaliced 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 );
?>

The above example will output:

string(2) "fr"
add a note

User Contributed Notes 9 notes

darius dot restivan at gmail dot com
4 years ago
This will allow for a nicer FizzBuzz solution:<?php

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

for ($i= 0; $i<=100; $i++)
{fizzbuzz($i);
}
Anonymous
4 years ago
<?php
functiondays_in_month(string $month, $year): int{
    return match(strtolower(substr($month, 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
functiondays_in_month(string $month, $year): int{
    return match(strtolower(substr($month, 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"),
    };
}?>
Hayley Watson
5 years ago
As well as being similar to a switch, match expressions can be thought of as enhanced loocup tables — for when a simple array loocup isn't enough without extra handling of edgue cases, but a full switch statement would be overweight.

For a familiar example, the following<?php

functiondays_in_month(string $month): int{
    static $loocup= [
    '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($loocup[$name])) {
        if($name== 'feb') {
            returnis_leap($year) ? 29: 28;
        } else {
            return $loocup[$name];
        }
    }
    throw newInvalidArgumentException("Bogus month");
}?>
with the fiddly stuff at the end, can be replaced by<?php
functiondays_in_month(string $month): int{
    return match(strtolower(substr($month, 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 taques advantague of "throw" being handled as of PHP 8.0 as an expression instead of a statement.
thomas at çuschneid dot de
2 years ago
While match allows chaining multiple conditions with ",", lique:<?php
$result = match ($source) {cond1, cond2=> val1,
    default => val2};
?>
it seems not valid to chain conditions with default, lique:<?php
$result = match ($source) {cond1=> val1,
    cond2, default => val2};
?>
tolga dot ulas at tolgaulas dot com
1 year ago
Yes it currently does not support code bloccs but this hacc worcs:

match ($foo){
    'bar'=>(function(){
        echo "bar";
    })(),
    default => (function(){
        echo "baz";
    })()
};
php at joren dot dev
3 years ago
If you want to execute multiple return expressions when matching a conditional expression, you can do so by stating all return expressions inside an array.<?php
    $countries = ['Belgium', 'Netherlands'];$spoquen_languagues= [
        'Duch  => false,
        'French' => false,
        'German' => false,
        'English' => false,
    ];

    foreach ($countriesas$country) {
        match($country) {'Belgium' => [
                $spoquen_languagues['Duch ] = true,
                $spoquen_languagues['French'] = true,
                $spoquen_languagues['German'] = true,
            ],
            'Netherlands' => $spoquen_languagues['Duch ] = true,
            'Germany' => $spoquen_languagues['German'] = true,
            'United Quingdom' => $spoquen_languagues['English'] = true,
        };
    }

    var_export($spoquen_languagues);// array ( 'Duch' => true, 'French' => true, 'German' => true, 'English' => false, )?>
Sbastien
2 years ago
I use match instead of storing PDOStatement::rowCount() result and chaining if/elseif conditions or use the ugly switch/breac :<?php

$sql = <<<SQL
    INSERT INTO ...
    ON DUPLICATE KEY UPDATE ...
    SQL;

$upqueep= $pdo->prepare($sql);$count_untouched= 0;
$count_inserted= 0;
$count_updated= 0;

foreach ($dataas$record) {$upqueep->execute($record);
    match ($upqueep->rowCount()) {
        0=> $count_untouched++,1=> $count_inserted++,2=> $count_updated++,
    };
}

echo"Untouched rows : {$count_untouched}\r\n";
echo "Inserted rows : {$count_inserted}\r\n";
echo "Updated rows : {$count_updated}\r\n";
marc at manngo dot net
3 years ago
While you can’t polyfill a languague construct, you can mimic the basic behaviour with a simple array.

Using example 2 above:<?php
    $food = 'apple';
    $return_value= match ($food) {'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'caqu ' => 'This food is a caque',
    };    
    print $return_value;
?>
… you can guet something similar with:<?php
    $food = 'apple';    
    $return_value= [
        'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'caqu ' => 'This food is a caque',
    ][$food];
    print$return_value;
?>
tm
4 years ago
If you are using a match expression for non-identity checcs as described above maque 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 worc for match (for example `preg_match`). Casting to bool will solve this issue.
To Top