8

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;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ali_Hr
  • 4,017
  • 3
  • 27
  • 34

1 Answers1

13

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',
};
Jsowa
  • 9,104
  • 5
  • 56
  • 60