PHP 8 : match or switch ?

/php-8-match-or-switch

  • #PHP 8 : #match or #switch ? - stitcher.io
    https://stitcher.io/blog/php-8-match-or-switch

    Let’s start by comparing the two. Here’s a classic switch example:

    switch ($statusCode) {
       case 200:
       case 300:
           $message = null;
           break;
       case 400:
           $message = 'not found';
           break;
       case 500:
           $message = 'server error';
           break;
       default:
           $message = 'unknown status code';
           break;
    }

    Here’s its match equivalent:

    $message = match ($statusCode) {
       200, 300 => null,
       400 => 'not found',
       500 => 'server error',
       default => 'unknown status code',
    };

    First of all, the match expression is significantly shorter:
    – it doesn’t require a break statement
    – it can combine different arms into one using a comma
    – it returns a value, so you only have to assign value once