在这种情况下PHP切换案例超过1个值

在这种情况下PHP切换案例超过1个值

问题描述:

I have another situation. I have a variable that holds the values ('Weekly', 'Monthly', 'Quarterly', 'Annual'), and I have another variable that holds the values from 1 to 10.

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

It isn't beautiful, because my code has a lot of duplicates. What I want:

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

How can I do it in PHP? Thank you in advance. Sorry for my english.

我有另一种情况。 我有一个包含值的变量('Weekly','Monthly','Quarterly','Annual'),我有另一个变量,它保存从1到10的值。 p>

  switch($ var2){
 case 1:
 $ var3 ='Weekly'; 
 break; 
 case 2:
 $ var3 ='Weekly'; 
 break; 
 case 3  :
 $ var3 ='每月'; 
中断; 
情况4:
 $ var3 ='季度'; 
中断; 
情况5:
 $ var3 ='季度'; 
中断;  
 //等等
} 
  code>  pre> 
 
 

它不漂亮,因为我的代码有很多重复。 我想要的是: p>

  switch($ var2){
 case 1,2,
 $ var3 ='Weekly'; 
 break; 
 case 3:\  n $ var3 ='每月'; 
中断; 
情况4,5:
 $ var3 ='季度'; 
中断; 
} 
  code>  pre> 
 
 我怎么能在PHP中做到这一点? 先感谢您。 对不起我的英文。 p> 
  div>

the simplest and probably 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, possibile 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.

Switch is also very handy for AB testing. Here the code for randomly testing 4 different versions of something:

$abctest = mt_rand(1, 1000);
switch ($abctest) {
   case ($abctest < 250):
     echo "A code here";
     break;
   case ($abctest < 500):
     echo "B code here";
     break;
   case ($abctest < 750):
     echo "C code here";
     break;
   default:
     echo "D code here";
     break;