Source: https://wallpaperaccess.com/full/6954292.jpg

Member-only story

PHP 8 Basics — The Match Expression

3 min readMay 24, 2022

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 a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, 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

--

--

No responses yet