PHP introduced an alternative of switch-case in the release of the 8th version.
In the release of the 8th version of PHP, the match() function is introduced which is the new alternative of switch-case. It is a powerful feature that is often the best decision to use instead of a switch-case. The match() function also works similarly to switch i.e, it finds the matching case according to the parameter passed in it.
Syntax :
$variable = match() { somecase => 'match_value' , anothercase => 'match_value', default => 'match_value', };
Example:
$value = match(1){ 1 => 'Hii..', 2 => 'Hello..', default => 'Match not found !', };
How match() function is different from switch-case?
- It uses an arrow symbol instead of a colon.
- It does not require a break statement.
- Cases are separated by commas instead of a break statement.
- The syntax of match() is terminated by a semi-colon.
- It returns some value based on the parameter provided.
- Strict type checking and case-sensitive.
- When there is no default value and match value, it will throw an error.
- Complex condition implementation and improved performance.
Note: The function match() is supported on PHP version 8 and above.
PHP code: The following example demonstrates the switch-case that will assign value to the variable $message on the basis of a value passed in the parameter of the switch()
PHP
<?php $day = 7; switch ( $day ) { case 1 : $message = 'Monday' ; break ; case 2 : $message = 'Tuesday' ; break ; case 3 : $message = 'Wednesday' ; break ; case 4 : $message = 'Thursday' ; break ; case 5 : $message = 'Friday' ; break ; case 6 : $message = 'Saturday' ; break ; case 7 : $message = 'Sunday' ; break ; default : $message = 'Invalid Input !' ; break ; } echo $message ; ?> |
Sunday
PHP code: The following code demonstrates the match() function which is executed only in PHP 8 or above.
PHP
<?php $day = 7; $message = match ( $day ) { 1 => 'Monday' , 2 => 'Tuesday' , 3 => 'Wednesday' , 4 => 'Thursday' , 5 => 'Friday' , 6 => 'Saturday' , 7 => 'Sunday' , default => 'Invalid Input !' , }; echo $message ; ?> |
Output:
Sunday