20

誰かが次のswitchステートメントを持つための最良の方法を提案できますか?2つの値を同時に比較できるかどうかはわかりませんが、これは理想的です。

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

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 に答える
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 に答える