Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch case more than one value in the case

People also ask

Can switch case Take 2 values?

With the integration of JEP 361: Switch Expressions in Java 14 and later, one can make use of the new form of the switch label using a comma between multiple values. People always mix up arrow labels and switch expressions. Sure they were introduced in the same JEP, but they are orthogonal features.

Can switch case have more than one default?

You cannot have more than one default statement in a switch.

Can we write condition in switch case in PHP?

PHP doesn't support this syntax. Only scalar values allowed for cases.

Is switch case faster than if PHP?

Due to the fact that "switch" does no comparison, it is slightly faster.


The simplest and probably the best way performance-wise would be:

switch ($var2) {
    case 1:
    case 2:
       $var3 = 'Weekly';
       break;
    case 3:
       $var3 = 'Monthly';
       break;
    case 4:
    case 5:
       $var3 = 'Quarterly';
       break;
}

Also, possible for more complex situations:

switch ($var2) {
    case ($var2 == 1 || $var2 == 2):
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case ($var2 == 4 || $var2 == 5):
        $var3 = 'Quarterly';
        break;
}

In this scenario, $var2 must be set and can not be null or 0


switch ($var2) {
       case 1 :
       case 2 :
          $var3 = 'Weekly';
          break;
       case 3 :
          $var3 = 'Monthly';
          break;
       case 4 :
       case 5 :
          $var3 = 'Quarterly';
          break;
}

Everything after the first matching case will be executed until a break statement is found. So it just falls through to the next case, which allows you to "group" cases.


If You're reading this and the year is 2021 and beyond, You're also using PHP > 8.0, you can now use the new match expression for this.

this could be

$var3 = match($var2){
    1, 2    => 'Weekly',
    3       => 'Monthly',
    4, 5    => 'Quarterly',
    default => 'Annually',
};

Please note that match does identity checks, this is the same as === compared to switch equality check which is ==.

read more about match expression here