PHP switch case more than one value in the case

前端 未结 3 613
南旧
南旧 2020-12-02 18:10

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



        
相关标签:
3条回答
  • 2020-12-02 18:33
    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.

    0 讨论(0)
  • 2020-12-02 18:34

    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

    0 讨论(0)
  • 2020-12-02 18:51

    Switch is also very handy for A/B testing. Here is the code for randomly testing four 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;
    
    0 讨论(0)
提交回复
热议问题