The New Match Expressions in PHP

Coding (PHP 8)


Is the new way to write conditions better than a switch statement?
 
/img/blog/the-new-match-expressions-in-php.jpeg

Why PHP 8?

 

On the 26th of November 2020, the core PHP team release the latest, fastest, and better version of the language yet.

 

Among all the amazing new features and keywords like Constructor property promotion, Nullsafe operator, and others, there is one that really stands out to the majority of developers.

 

I am talking about the match expression

 

Match expression

 

 

 

 

Think of the match expression as an evolution of the switch statement.

 

What it does, is to evaluate a subject expression and, depending on the cases, branch out to a different block or code or statement.

 

Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==).

 

$food = 'cake';

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

var_dump($returnValue);
// string(19) "This food is a cake"

 

Why use it?

 

There are many positive aspects of using this new feature of the language.

 

For example, one of the most annoying things about using the switch statement was that we must not forget to use the to break the code’s block.

 

No more breaks!

 

If we do not do it, the code will keep running on the following case.

 

This of course led to errors and unexpected results.

 

$i = 0;switch ($i) {
    case 0:
        echo "i equals 0";       
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}"i equals 0"
"i equals 1"

 

A match expression returns a value:

 

You have seen it in the example above, the inside of the match block looks like a classic array, and the value of the matching condition is the value actually returned into the variable.

 

Match expression also handles non-identity conditional cases, as long as its conditional expression is true.

 

Here is an example.

 

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

 

Like the switch, any arm may contain multiple expressions separated by a comma.

 

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

 

Another feature inherited from the switch is the default case.

 

$expressionResult = match ($condition) {
    1, 3 => getFromEvens(),
    2, 4 => getFromOdds(),
    default => GetAll(),
};

 

If the condition is not identical to any of the previous cases (1, 2, 3, or 4) then and only then the function GetAll() will be invoked.

 

Do not put multiple default conditions though as it will throw an error!

 

A better way to handle this is by wrapping the expression inside a try-catch block

 

$condition = 5;

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

 

Cons

 

There aren’t really any cons to using it.

 

In my opinion, the syntax is cleaner than the one from the switch statement and it handles results in a more elegant manner.

 

The only reason I wouldn’t use it would be in case I need just 2 or 3 cases.

 

In that eventuality, I might opt for a couple of single if statements instead.

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (PHP 8) Oct 19, 2020

PHP 8 JIT [most expected feature]

See details
Coding (PHP 8) Nov 13, 2022

How to fix the PHP fatal error: allowed memory exhausted?

See details
Coding (PHP 8) Nov 16, 2022

This is why Symfony 6 is perfect for your next project (PHP Framework)

See details
Get my free books' review to improve your skill now!
I'll do myself