检查变量是否与多个值不同

Let*_*yer 3 php variables if-statement

如果我想采取行动,如果变量不是0,1或2的PHP,我该怎么办?我的if语句不起作用.谢谢!

Art*_*cto 7

if (($var != 0) && ($var != 1) && ($var != 2)) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

要么...

if (!in_array($var, array(0, 1, 2))) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

参见逻辑运算符.

  • @Leticia:您还应该在下次发布您的代码,以便我们可以看到您出错的地方. (2认同)

cHa*_*Hao 5

最直截了当的方式:

if ($x != 0 && $x != 1 && $x != 2)
{
    // take action!
}
Run Code Online (Sandbox Code Playgroud)

如果您知道您的变量是int,那么您也可以这样做:

if ($x < 0 || $x > 2)
{
    // take action!
}
Run Code Online (Sandbox Code Playgroud)