DEV Community

Cover image for PHP Match statement
Damian Brdej
Damian Brdej

Posted on

2 1

PHP Match statement

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

Match statement

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

multiple conditions

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?

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay