Awesome! use Match Expression for simplify your code in PHP 8
Irpan Abdul Rahman
Posted on August 1, 2024
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
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
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.
Posted on August 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
November 28, 2024