Open In App

Is there any alternate of switch-case in PHP ?

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? 

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
   
$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;
?>

Output
Sunday

PHP code: The following code demonstrates the match() function which is executed only in PHP 8 or above. 




<?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

Article Tags :