[英]Check if variable is different from several values
If I want to take an action if php if a variable isn't 0,1, or 2, how would I do that? 如果我想采取行动,如果变量不是0,1或2的PHP,我该怎么办? my if statement isn't working. 我的if语句不起作用。 Thanks! 谢谢!
if (($var != 0) && ($var != 1) && ($var != 2)) {
//...
}
or... 要么...
if (!in_array($var, array(0, 1, 2))) { /* ... */ }
See logical operators . 参见逻辑运算符 。
The most straightforward way: 最直截了当的方式:
if ($x != 0 && $x != 1 && $x != 2)
{
// take action!
}
If you know your variable is an int, then you could also do like: 如果您知道您的变量是int,那么您也可以这样做:
if ($x < 0 || $x > 2)
{
// take action!
}
Use the &&
operator to chain tests, and test non-equality with !==
which checks type and value: 使用&&
运算符链接测试,并使用!==
测试不相等,它检查类型和值:
if( $n !== 0 && $n !== 1 && $n !== 2 ) {
// it's not any of those values.
}
The ==
operator will coerce values, so all the following are true: ==
运算符将强制赋值,因此以下所有都是正确的:
And so on. 等等。 See comparison operators for more information about ==
vs. ===
. 有关==
与===
更多信息,请参阅比较运算符 。 Also check the table "Comparison with Various Types" to better understand how types are coerced if you are comparing non-numbers. 还要检查“与各种类型的比较”表,以便在比较非数字时更好地了解类型的强制类型。 Only you can determine if if( $n < 0 || $n > 2 )
will meet your needs. 只有您可以确定if( $n < 0 || $n > 2 )
是否满足您的需求。 (Well, we can help, but we need more details.) (嗯,我们可以提供帮助,但我们需要更多细节。)
See logical operators for more on &&
and ||
有关&&
和||
更多信息,请参阅逻辑运算符 . 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.