PHP 8: Stop switch’ing, start match’ing

No, this isn’t an ad for Tinder! 🥸

As of PHP 8.0 a new expression named match is available. It’s similar to the switch statement but match will probably become your number one choice once you know the differences.

Let’s take a look at a the following switch example:

$value = '';
switch ( $value ) {
    case 0:
    case '0':
        $result = 0;
        break;
    case null:
        $result = null;
        break;
    case '1':
         $result ='1';
        break;
    default:
         $result ='default';
}Code language: PHP (php)

What’s the value of $result?

.

.

.

Correct, it’s not default but null. Why? Because switch is doing loose (==) checks. 😖

The same example with match:

$value  = '';
$result = match ( $value ) {
    0, '0'  => 0,
    null    => null,
   '1'      => '1',
    default => 'default',
};Code language: PHP (php)

match does strict type checks by default and and so the output will be the expected default case. 🤩

Another benefit? It’s so much shorter as it does not have break or return statements. This should look familiar when you work with short closures (arrow functions) which were introduced in PHP 7.4. The value only needs to be assigned once. And you only have to combine multiple conditions by a comma.

match fixes also another quirk of switch: Any unhandled case will throw an UnhandledMatchError exception. This plus the strict type checks should prevent any bugs which may otherwise get unnoticed and cause unexpected behaviour of your code.

One important note: match does not support multi-line only one expression like arrow functions. But I guess if you have already used switch with more than one expression you are already doing-it-wrong. 🤫

So, was this is a match?