As of PHP8.0 a new expression was introduced, it is a powerful feature and it will often be the better choice compared to using switch.
(PHP 8) The
match
expression branches evaluation based on an identity check of a value. Similarly to aswitch
statement, amatch
expression has a subject expression that is compared against multiple alternatives. Unlikeswitch
, it will evaluate to a value much like ternary expressions. Unlikeswitch
, the comparison is an identity check (===
) rather than a weak equality check (==
). Match expressions are available as of PHP 8.0.0.
It is because both match
and switch
have specific use cases that aren’t covered by the other.
So what are the differences between them? Comparing the two would go like this. First, this is the classic switch
example:
And here is the match
equivalent:
Firstly, the match
expression is significantly shorter:
- it does not require a break statement to prevent fallthrough