DEV Community

Cover image for The match expression (From the office!)
anastasionico
anastasionico

Posted on

The match expression (From the office!)

The match expression (From the office!)

Hi, I am Nico,

I am a Senior Engineer for a ticket broker based in London.

From the office! is a daily (almost) posting routine that I keep to journal about the tech things I have been doing in my day-to-day office life.

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

A match expression returns a value:

You have seen it in the example above, the inside of the match block looks like an 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',
};
Enter fullscreen mode Exit fullscreen mode

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,
};
Enter fullscreen mode Exit fullscreen mode

Another feature inherited from the switch is the default case.

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

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

What is your take?

Have you used the match expression already?

What was its use case of it?

Show your example in the comment below.

Conclusion

I have been a web developer for almost a decade now.

Working with world-class businesses and award-winning marketing agencies situated in the heart of London.

Also, I write articles and tutorials on my blog and online communities and help businesses build their presence online.

Click here to read more than 100+ of my blog post

Latest comments (0)