Search code examples
phpphp-8

How to use match expression instead of switch expression


We can use match expression instead of switch case in PHP 8.

How to write match expression correctly for the following switch case?

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;
}

Solution

  • There is an important thing that must remember with match. It is type sensitive, not as a switch statement. Thus it's very important to cast the variable properly. In the case of HTTP codes often it is sent in string format, e.g. "400".

    It may give a lot of pain during debugging when we don't know about it. If $statusCode was a string, the default option would be always invoked. My modified version of an accepted answer:

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