DEV Community

Cover image for Awesome! use Match Expression for simplify your code in PHP 8
Irpan Abdul Rahman
Irpan Abdul Rahman

Posted on

Awesome! use Match Expression for simplify your code in PHP 8

PHP 8 introduces the match expression, which is a more powerful and concise alternative to the traditional switch statement.

  • The traditional switch statement requires break statements and can be more verbose.
  • The new match expression simplifies the syntax and returns a value directly.

for the example when we use switch case statement :

function getDayTypeWithSwitch(int $day): string
{
    switch ($day) {
        case 1:
        case 7:
            return 'weekend';
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            return 'weekday';
        default:
            return 'unknown';
    }
}

echo getDayTypeWithSwitch(8); // Output: unknown
echo getDayTypeWithSwitch(7); // Output: weekend
echo getDayTypeWithSwitch(4); // Output: weekday
Enter fullscreen mode Exit fullscreen mode

and the we comparing use match expression :

function getDayWithMatch(int $day): string
{
    return match ($day) {
        1, 7 => 'weekend',
        2, 3, 4, 5, 6 => 'weekday',
        default => 'unknown',
    };
}

echo getDayWithMatch(8); // Output: unknown
echo getDayWithMatch(7); // Output: weekend
echo getDayWithMatch(4); // Output: weekday
Enter fullscreen mode Exit fullscreen mode

awesome you should be try it !

✅ 𝐁𝐞𝐧𝐞𝐟𝐢𝐭𝐬 𝐨𝐟 𝐔𝐬𝐢𝐧𝐠 𝐌𝐚𝐭𝐜𝐡 𝐄𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧𝐬

👉 𝐂𝐨𝐧𝐜𝐢𝐬𝐞 𝐒𝐲𝐧𝐭𝐚𝐱: Reduces boilerplate code by eliminating the need for break statements.
👉 𝐑𝐞𝐭𝐮𝐫𝐧𝐬 𝐕𝐚𝐥𝐮𝐞𝐬: Can return values directly, making the code more expressive and functional.
👉 𝐒𝐭𝐫𝐢𝐜𝐭 𝐂𝐨𝐦𝐩𝐚𝐫𝐢𝐬𝐨𝐧𝐬: Uses strict comparisons (===) by default, avoiding type coercion issues.

By using match expressions in PHP 8, you can write cleaner, more efficient, and more readable code.

How do you like the new match expressions? Have you used them in your project yet? Share your experience in the comments below.

Top comments (2)

Collapse
 
denys_bochko profile image
Denys Bochko

That's interesting, although I find the case statements more organized: in my opinion what's inline is more difficult to read than what's in column.
Another question though: is that only valid for single return statements? what if there is more logic involved?

Collapse
 
bentesolution profile image
Irpan Abdul Rahman

Yes you're right. but for me, match expressions are better for returning simple values or expressions.

Of course, match is limited to a single expression per arm, but you can add logic using function calls or anonymous functions. for more complex logic, consider using a switch statement or separating the logic into functions.