switch statement with two variables at a time

后端 未结 6 1668

Could someone suggest the best way to have the following switch statement? I don\'t know that it\'s possible to compare two values at once, but this would be ideal:

相关标签:
6条回答
  • 2020-12-09 05:01
    var $var1 = "something";
    var $var2 = "something_else";
    switch($var1.$var2) {
    case "somethingsomething_else":
        ...
        break;
    case "something...":
        break;
    case "......":
        break;
    }
    
    0 讨论(0)
  • 2020-12-09 05:02

    Found at http://www.siteduzero.com/forum/sujet/switch-a-plusieurs-variables-75351

    <?php
    $var1 = "variable1";
    $var2 = "variable2";
    $tableau = array($var1, $var2);
    
    switch ($tableau){
        case array("variable1", "variable2"):
            echo "Le tableau correspond !";
        break;
    
        case array(NULL, NULL):
            echo "Le tableau ne correspond pas.";
        break; 
    }
    ?>
    
    0 讨论(0)
  • 2020-12-09 05:04

    You can change the order of the comparison, but this is still not ideal.

        switch(true)
        {
          case ($color == 'blue' and $size == 'small'):
            echo "blue and small";
            break;
          case ($color == 'red' and $size == 'large'):
            echo "red and large";
            break;
          default:
            echo 'nothing';
            break;
        }
    
    0 讨论(0)
  • 2020-12-09 05:05

    Your other option (though not pretty) is to nest the switch statements:

    switch($color){
        case "blue":
            switch($size):
                case "small":
                //do something
                break;
        break;
    }
    
    0 讨论(0)
  • 2020-12-09 05:13

    Doesn't work. You could hack around it with some string concatentation:

    switch($color . $size) {
       case 'bluesmall': ...
       case 'redlarge': ...
    }
    

    but that gets ugly pretty quick.

    0 讨论(0)
  • 2020-12-09 05:14

    Using the new array syntax, this looks almost like what you want:

    switch ([$color, $size]) {
        case ['blue', 'small']:
            echo 'blue and small';
        break;
    
        case ['red', 'large'];
            echo 'red and large';
        break;
    }
    
    0 讨论(0)
提交回复
热议问题