PHP › PHP 8 Features (Attributes, Enums, Match, Nullsafe Operator)
What is the match expression introduced in PHP 8, and how does it improve upon the traditional switch statement?
BeginnerAnswer
The match expression compares a value against several possible conditions and returns a corresponding result, similar in purpose to a switch statement, but match uses strict type comparison by default rather than loose comparison, does not require a break statement to prevent falling through to the next case, and can be used directly as an expression that returns a value, making it more concise and less error prone than the equivalent switch statement for many common use cases.
$result = match ($status) {
'pending' => 'Order is being processed',
'shipped' => 'Order is on its way',
default => 'Unknown status',
};Real-world example An order status display function uses a match expression to cleanly convert a status code directly into a corresponding user friendly message, avoiding the verbose break statements and loose comparison pitfalls that the equivalent switch statement would have required.