欢迎各位兄弟 发布技术文章
这里的技术是共享的
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": ...
}
正确答案
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;
}
在某些情况下,它比无限的 if-elseif-else
链更具可读性。
来自 https://www.coder.work/article/724997