我的IF语句出现问题,虽然这是不正确的,但它始终为TRUE。我正在使用OR运算符,因为我想在IF语句中捕获两种可能的场景。
数组字符串ad_status为“1”但返回使用-3以下,我期待IF为FALSE。如果我从IF中删除OR和第二个语句,则IF的结果是正确的。
我做错了什么?感谢。
if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
其他: 我想要做的是退出函数(这里没有看到)如果ad_status不等于1或4.如果它等于1或4以外的任何其他值,则IF语句应该返回TRUE并退出。 ad_status可以是0到4之间的任何值。
答案 0 :(得分:8)
您所说的是not 1
或not 4
的任何值都应返回true。
对于'1',您会收到声明
if( 1 != 1 || 1 != 4)
转换为
if( false || true )
当然是真的。
您需要的是:
if(!($value == 1 || $value==4))
相同
if($value != 1 && $value != 4)
答案 1 :(得分:2)
那里没有错误。
如果ad_status == 1
那么你的第二个条件会让你进入If
$getadstatus['ad_status'] != "4"
是真的,因此你会得到return -3;
如果我得到你想要的,你应该使用AND
if ( $a!= 1 AND $a!= 4 )
答案 2 :(得分:2)
你检查:
ad_status != 1 -> FALSE
ad_status != 4 -> TRUE
if (FALSE OR TRUE)
始终为TRUE
。
要达到预期效果,请用AND替换OR:
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
答案 3 :(得分:2)
它始终是真的,因为任何值都不能同时为'1'和'4'。
答案 4 :(得分:2)
您应该使用&&
运算符,因为请使用!=
。如果您想使用||
,您可以这样写:
if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))
答案 5 :(得分:2)
您想使用&&
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
答案 6 :(得分:2)
我个人更喜欢在IF状态中使用in_array而不是OR。例如:
$array = array(1,4);
if (!in_array($getadstatus['ad_status'], $array)) {
// do whatever
}
答案 7 :(得分:0)
嗯,好吧,我想我明白了。我试图太聪明了。我想使用单个IF语句来检查两个不相关的条件。如果ad_status不等于1或4,则返回-3并退出该函数。
好的,没问题,可以表达,只需像你写的那样表达:
$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
return -3;
}
所以!
(不是)应该在你的句子中写的整个OR比较。这可能是你原本想到的代码。但是由于顺序很重要,在使用not(!
)运算符之前,条件的另一部分需要在括号内进行计算。
添加了:
条件或表达式越多,子条件越多,它就越复杂。但是,你制定复杂条件的次数越多,你就会越好。要训练,您总是可以在多行上分割条件并为其标记(变量)分配:
$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;
对于生产代码,这可能过度使用,但由于作者总是选择如何编写某些内容,因此您可以执行语言允许的任何操作。