PHP Match statement

PHP 8 introduces match expression which is similar to switch. Let's look into the differences between these two:

More strictness

Match compares values strictly (===) instead of loosely (==) as the switch statement does.

In Match Unknown values cause errors, so if you forget to check for a value and you don't have a default value PHP will throw an UnhandledMatchError exception

Returns value

Match returns value so you have to It once instead in each case like in switch statement, which make code much shorter

Combining conditions

Match arms do not fall-through to later cases the way switch statements do, but you can combine conditions on the same line, separated by commas to achieve the same effect

Single-line expressions

Only single-line expressions are allowed in Match statement. In switch you can have multiple expression till the 'break' statement

Summary

In my opinion Match is better option than switch in situations where you don't need multiple-line expressions.

And what do you think about this "new" feature?

26