20

有人可以建议使用以下 switch 语句的最佳方法吗?我不知道是否可以一次比较两个值,但这将是理想的:

switch($color,$size){
    case "blue","small":
        echo "blue and small";
    break;

    case "red","large";
        echo "red and large";
    break;
}

这可以与以下内容相媲美:
if (($color == "blue") && ($size == "small")) {
    echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
    echo "red and large";
}

更新 我意识到我需要能够否定($color !== "blue")和比较,而不是将变量等同于字符串。

4

6 回答 6

55

使用新的数组语法,这看起来几乎就像您想要的那样:

switch ([$color, $size]) {
    case ['blue', 'small']:
        echo 'blue and small';
    break;

    case ['red', 'large'];
        echo 'red and large';
    break;
}
于 2015-05-13T08:10:50.287 回答
35

您可以更改比较的顺序,但这仍然不理想。

    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;
    }
于 2012-09-26T04:56:19.517 回答
17

不工作。你可以用一些字符串连接来破解它:

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

但这很快就会变得丑陋。

于 2012-09-26T04:56:29.717 回答
7

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; 
}
?>
于 2013-05-13T07:55:38.567 回答
1

您的另一个选择(虽然不漂亮)是嵌套 switch 语句:

switch($color){
    case "blue":
        switch($size):
            case "small":
            //do something
            break;
    break;
}
于 2015-01-19T23:08:02.773 回答
0
var $var1 = "something";
var $var2 = "something_else";
switch($var1.$var2) {
case "somethingsomething_else":
    ...
    break;
case "something...":
    break;
case "......":
    break;
}
于 2012-09-26T04:58:09.840 回答