[英]PHP: issue with switch with range
I would like to differ between the following cases in PHP using a switch statement. 我想在以下使用switch语句的PHP中区分以下情况。 Can someone here help and tell me how I have to change this to get it working with numeric ranges (integers) ? 有人可以帮忙告诉我如何更改此设置以使其在数字范围(整数)下工作吗?
So far I have the following but guess this needs modification because of the ranges: 到目前为止,我有以下内容,但由于范围原因,我猜这需要修改:
switch($myVar)
{
case(<0):
// do stuff
break;
case(<10):
// do stuff
break;
case(<20):
// do stuff
break;
case(<30):
// do stuff
break;
case(<999):
// do stuff
break;
default:
// do stuff
break;
}
Many thanks for any help with this, Tim 蒂姆,非常感谢您对此提供的任何帮助
You can do it like this: 您可以这样做:
$myVar = 50;
switch (true) {
case($myVar < 0):
// do stuff
break;
case($myVar < 10):
// do stuff
break;
case($myVar < 20):
// do stuff
break;
case($myVar < 30):
// do stuff
break;
case($myVar < 999):
// do stuff
break;
default:
// do stuff
break;
}
There are a few good example about that in the comments of the manual . 手册的注释中有一些很好的例子。
Use the in_array($myVar,range(100,200))
to check whether the value exists in the range. 使用in_array($myVar,range(100,200))
检查值是否在范围内。
$myVar = 50;
switch (true) {
case(in_array($myVar,range(0,10))):
// do stuff
break;
case(in_array($myVar,range(20,30))):
// do stuff
break;
case(in_array($myVar,range(30,900))):
// do stuff
break;
default:
// do stuff
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.