欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php switch语句两个变量 两个参数 有大用 有大大用

PHP switch 语句可以接受两个参数吗?例如:

switch (firstVal, secondVal){

    case firstVal == "YN" && secondVal == "NN":
    thisDesc = "this is the outcome: YN and NN";
    break;

    case firstVal == "YY" && secondVal == "NN":
    thisDesc = "this is the outcome: YY and NN";
    break;
}
   

非常感谢,我已经很多年没有用过 PHP 了!


   

最佳答案    


   

不,你不能。一个 switch 语句,如

switch ($a) {
  case 1:
  break;
  case 2:
  break;
}
   

实际上等同于

if ($a == 1) {
} else if ($a == 2) {
}
   

正确答案   你可以使用稍微不同的结构

switch (true) {
  case $firstVal == "YN" && $secondVal == "NN":
  break;
  case $firstVal == "YY" && $secondVal == "NN":
  break;
}
   

相当于

if (true == ($firstVal == "YN" && $secondVal == "NN")) {
} else if (true == ($firstVal == "YY" && $secondVal == "NN")) {
}
     


   

正确答案  只需连接两个输入并测试连接值:     


   

switch ($firstval . $secondval) {

        case "YNNN": ...

        case "YYNN": ...

}


正确答案  

   

  1. switch(true)

  2.    {

  3.      case ($color == 'blue' and $size == 'small'):

  4.        echo "blue and small";

  5.        break;

  6.      case ($color == 'red' and $size == 'large'):

  7.        echo "red and large";

  8.        break;

  9.      default:

  10.        echo 'nothing';

  11.        break;

  12.    }


   

在某些情况下,它比无限的 if-elseif-else 链更具可读性。

来自  https://www.coder.work/article/724997


普通分类: