是否有一种方法使用'OR'操作符或等价的PHP开关?
例如,这样的东西:
switch ($value) {
case 1 || 2:
echo 'the value is either 1 or 2';
break;
}
是否有一种方法使用'OR'操作符或等价的PHP开关?
例如,这样的东西:
switch ($value) {
case 1 || 2:
echo 'the value is either 1 or 2';
break;
}
当前回答
如果你必须使用||开关,那么你可以尝试:
$v = 1;
switch (true) {
case ($v == 1 || $v == 2):
echo 'the value is either 1 or 2';
break;
}
如果不是,你更喜欢的解决方案是
switch($v) {
case 1:
case 2:
echo "the value is either 1 or 2";
break;
}
问题是这两种方法在处理大型案件时效率都不高。想象一下,从1到100,这是完美的
$r1 = range(1, 100);
$r2 = range(100, 200);
$v = 76;
switch (true) {
case in_array($v, $r1) :
echo 'the value is in range 1 to 100';
break;
case in_array($v, $r2) :
echo 'the value is in range 100 to 200';
break;
}
其他回答
http://php.net/manual/en/control-structures.switch.php 例子
$today = date("D");
switch($today){
case "Mon":
case "Tue":
echo "Today is Tuesday or Monday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
default:
echo "No information available for that day.";
break;
}
匹配表达式(PHP 8)
PHP 8引入了一个新的匹配表达式,它与switch类似,但语法更短,区别如下:
不需要break语句 使用逗号组合条件 返回一个值 具有严格的类型比较 要求比较是详尽的(如果没有找到匹配,UnhandledMatchError将被抛出)
例子:
match ($value) {
0 => '0',
1, 2 => "1 or 2",
default => "3",
}
Try
switch($value) {
case 1:
case 2:
echo "the value is either 1 or 2";
break;
}
switch ($value)
{
case 1:
case 2:
echo "the value is either 1 or 2.";
break;
}
这就是所谓的“穿过”案例块。这个术语存在于大多数实现switch语句的语言中。
使用以下代码:
switch($a) {
case 1:
case 2:
.......
.......
.......
break;
}
1和2都调用该块。