The match
expression in PHP 8 provides a more powerful and expressive alternative to switch
statements. It's especially useful for simple conditional returns.
$statusCode = 404;
$message = match ($statusCode) {
200, 300 => 'Success',
400 => 'Bad request',
404 => 'Not found',
500 => 'Server error',
default => 'Unknown status code',
};
echo $message; // Outputs: Not found
match
expressions are more concise than switch
statements, don't fall through, and return a value directly.