Advertisement
Beginner 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?

Short answer

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…

Save PHP mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What happens if a match expression does not have a matching condition and no default case is provided?
  • Can a single match arm handle multiple possible values?
Related topics