一次带有两个变量的 switch 语句

2022-01-19 00:00:00 switch-statement php

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

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:

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

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


这可以与以下内容相媲美:


This could be comparable to:

if (($color == "blue") && ($size == "small")) {
    echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
    echo "red and large";
}


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


Update I realized that I'll need to be able to negate ($color !== "blue") and compare as opposed to equating variables to strings.

推荐答案

你可以改变比较的顺序,但这仍然不理想.

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

相关文章