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