奇怪的php if语句问题

Jas*_*vis 4 php conditional

if($country == 224 || $country == 223 || $country == 39 && $zip == '' ){
    $_SESSION['sess_msg'] = "Please enter a Valid zipcode";
    header("location: $SITE_PATH?p=account.profile.name");
    exit;
}
Run Code Online (Sandbox Code Playgroud)
variable   value
--------   -----
$country     224
$zip       11111

我知道这$zip不是空的,但代码执行就像它一样.我甚至在调试语句中将其打印到浏览器以验证它是否具有值.

是什么导致我的程序表现得好像$zip没有价值?

Gum*_*mbo 26

&&经营者具有更高的优先级||运营商.所以你的表达式等于:

$country == 224 || $country == 223 || ($country == 39 && $zip == '')
Run Code Online (Sandbox Code Playgroud)

解决方案:

($country == 224 || $country == 223 || $country == 39) && $zip == ''
Run Code Online (Sandbox Code Playgroud)

  • 我想补充一点:如果编译器或解释器记住运算符优先级,程序员就不应该对此进行中继.如果一个同事误解了优先顺序可能会引入难以维护的错误.我的建议是使用肠胃外给药来解决任何歧义,以便让你的同事对你在第一眼看到的内容充满信心. (9认同)

Geo*_*ker 15

您是否尝试过使用括号命令操作?

($country == 22 || $country == 223 || $country == 39) && ($zip == '') 
Run Code Online (Sandbox Code Playgroud)


Bol*_*wyn 9

问题是PHP检查你的布尔运算符顺序.首先它看到一个条件,然后是一个OR,它认为:哎呀,是的!条件得到满足.我为什么要费心阅读并执行剩下的这些东西?

实际上,这是一个功能.想想这个星座:

if (something_probable () OR something_very_expensive_to_compute ())
Run Code Online (Sandbox Code Playgroud)

如果第一个已经通过了测试,那么很好的PHP不评估第二个.

尝试使用括号:

if (($country == 224 || $country == 223 || $country == 39) && $zip == '' ){
Run Code Online (Sandbox Code Playgroud)

干杯,


Tom*_*igh 5

&&具有比||更高的运算符优先级 ,所以你有效地说:

if($country == 224 || $country == 223 || ($country == 39 && $zip == '' ))
Run Code Online (Sandbox Code Playgroud)


Gab*_*osa 5

我喜欢第一个答案,但无论如何都不会更具可读性:

<?php

$need_zip_code = array(224, 222, 332, 222/* etc....*/);

if (in_array($country, $need_zip_code) &&  $zip === '') {
 // do your stuff....
}


?> 
Run Code Online (Sandbox Code Playgroud)