一次包含两个变量的 switch 语句

2022-08-30 18:40:17

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

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")


答案 1

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

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

    case ['red', 'large'];
        echo 'red and large';
    break;
}

答案 2

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

    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;
    }

推荐