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 image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs