PHP switch case 超过 1 个值的情况
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4163188/
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
PHP switch case more than 1 value in the case
提问by Alex Pliutau
I have a variable that holds the values ('Weekly', 'Monthly', 'Quarterly', 'Annual'), and I have another variable that holds the values from 1 to 10.
我有一个保存值的变量(“每周”、“每月”、“季度”、“每年”),我还有另一个变量保存从 1 到 10 的值。
switch ($var2) {
case 1:
$var3 = 'Weekly';
break;
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
$var3 = 'Quarterly';
break;
case 5:
$var3 = 'Quarterly';
break;
// etc.
}
It isn't beautiful, because my code has a lot of duplicates. What I want:
它并不漂亮,因为我的代码有很多重复。我想要的是:
switch ($var2) {
case 1, 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4, 5:
$var3 = 'Quarterly';
break;
}
How can I do it in PHP? Thank you in advance. Sorry for my english.
我怎样才能在 PHP 中做到这一点?先感谢您。对不起我的英语不好。
回答by Hannes
the simplest and probably best way performance wise would be:
最简单也可能是最好的性能明智的方法是:
switch ($var2) {
case 1:
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
case 5:
$var3 = 'Quarterly';
break;
}
also, possibile for more complex situations:
此外,可能用于更复杂的情况:
switch ($var2) {
case ($var2 == 1 || $var2 == 2):
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case ($var2 == 4 || $var2 == 5):
$var3 = 'Quarterly';
break;
}
in this scenario, $var2 must be set and can not be null or 0
在这种情况下,必须设置 $var2 并且不能为 null 或 0
回答by deceze
switch ($var2) {
case 1 :
case 2 :
$var3 = 'Weekly';
break;
case 3 :
$var3 = 'Monthly';
break;
case 4 :
case 5 :
$var3 = 'Quarterly';
break;
}
Everything after the first matching case will be executed until a break statement is found. So it just falls through to the next case, which allows you to "group" cases.
将执行第一个匹配案例之后的所有内容,直到找到 break 语句。所以它只是落入下一个案例,它允许您“分组”案例。
回答by Soccerwidow
Switch is also very handy for AB testing. Here the code for randomly testing 4 different versions of something:
Switch对于AB测试也非常方便。这里是随机测试 4 个不同版本的代码:
$abctest = mt_rand(1, 1000);
switch ($abctest) {
case ($abctest < 250):
echo "A code here";
break;
case ($abctest < 500):
echo "B code here";
break;
case ($abctest < 750):
echo "C code here";
break;
default:
echo "D code here";
break;