在php中是否有任何语法或命令来检查数字是否在一组数字中?

Che*_*ong 4 php comparison range set

我来自另一种语言,所以我在php上错过了这个功能.例如,如果我想检查数字是否为2,4,介于7到10或15之间,我想将其表达为:

if ($x in [2, 4, 7...10, 15]) { do_something(); }
Run Code Online (Sandbox Code Playgroud)

代替:

if ($x == 2 || $x == 4 || ($x >= 7 && $x <= 10) || $x == 15) { do_something(); }
Run Code Online (Sandbox Code Playgroud)

要么:

switch ($x) {
case 2:
case 4:
case 7:
case 8:
case 9:
case 10:
case 15:
    do_something();
    break;
}
Run Code Online (Sandbox Code Playgroud)

甚至:

switch (true) {
case ($x == 2):
case ($x == 4):
case ($x >= 7 && $x <= 10):
case ($x == 15):
    do_something();
    break;
}
Run Code Online (Sandbox Code Playgroud)

在PHP中有没有办法做到这一点或类似的解决方法?我在代码中经常使用这种比较,并且"in set"格式使我的代码更具可读性并且更不容易出错(写入7...10比写入更安全x >= 7 && x <= 10).谢谢.

小智 8

您可以使用in_array():

if (in_array(3, [1, 2, 3, 7, 8, 9, 10, 15])) { 
    do_something(); //true, so will do
}
Run Code Online (Sandbox Code Playgroud)