php 一次包含两个变量的 switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12594763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
switch statement with two variables at a time
提问by d-_-b
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 语句的最佳方法吗?我不知道可以一次比较两个值,但这将是理想的:
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";
}
UpdateI realized that I'll need to be able to negate ($color !== "blue")and compare as opposed to equating variables to strings.
更新我意识到我需要能够否定($color !== "blue")和比较,而不是将变量等同于字符串。
回答by Renaat De Muynck
Using the new array syntax, this looks almost like what you want:
使用新的数组语法,这看起来很像您想要的:
switch ([$color, $size]) {
case ['blue', 'small']:
echo 'blue and small';
break;
case ['red', 'large'];
echo 'red and large';
break;
}
回答by Scuzzy
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;
}
回答by Marc B
Doesn't work. You could hack around it with some string concatentation:
不起作用。你可以用一些字符串连接来破解它:
switch($color . $size) {
case 'bluesmall': ...
case 'redlarge': ...
}
but that gets ugly pretty quick.
但这很快就会变得丑陋。
回答by Stikmou
Found at http://www.siteduzero.com/forum/sujet/switch-a-plusieurs-variables-75351
位于 http://www.siteduzero.com/forum/sujet/switch-a-plusieurs-variables-75351
<?php
$var1 = "variable1";
$var2 = "variable2";
$tableau = array($var1, $var2);
switch ($tableau){
case array("variable1", "variable2"):
echo "Le tableau correspond !";
break;
case array(NULL, NULL):
echo "Le tableau ne correspond pas.";
break;
}
?>
回答by Ryre
Your other option (though not pretty) is to nest the switch statements:
您的另一个选择(虽然不漂亮)是嵌套 switch 语句:
switch($color){
case "blue":
switch($size):
case "small":
//do something
break;
break;
}
回答by Raj Adroit
var $var1 = "something";
var $var2 = "something_else";
switch($var1.$var2) {
case "somethingsomething_else":
...
break;
case "something...":
break;
case "......":
break;
}

