IF语句中的PHP逻辑运算符

时间:2014-07-18 09:49:07

标签: php if-statement operators

我有以下代码:

PHP

if($brand == 'ABC' && $main == ''){
    include '../_inc/report.php';
}else
if($brand == 'ABC' && $main == 'TRUE'){
    include '../_inc/analysis.php';
}else
if($brand == 'XYZ' || $brand == '123' || $brand == '1A9' && $main == ''){
    include '../_inc/report.php';
}else
if($brand == 'XYZ' || $brand == '123' || $brand == '1A9' && $main == 'TRUE'){
    include '../_inc/analysis.php';
}

信息传递到URL中的PHP页面,例如:

?br=ABC&cr=MAY2014&pd=NOV2013&mn=TRUE
?br=XYZ&cr=MAY2014&pd=NOV2013&mn=TRUE

处理如下:

$brand = $_GET['br'];
$main = $_GET['mn'];

如果发生$brand = ABC and $main = TRUE,那么analysis.php成功加载(这是正确的)。

但是,如果$brand = XYZ and $main = TRUE加载了report.php,那么这不是我期望或需要的行为。

这是与操作员的工作方式有关还是我的代码不正确。欢迎任何帮助和反馈。

5 个答案:

答案 0 :(得分:1)

你应该用适当的brckets写条件。

尝试以下代码

if($brand == 'ABC' && $main == ''){
    include '../_inc/report.php';
}else
if($brand == 'ABC' && $main == 'TRUE'){
    include '../_inc/analysis.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == ''){
    include '../_inc/report.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == 'TRUE'){
    include '../_inc/analysis.php';
}

答案 1 :(得分:1)

试试这个

if($brand == 'ABC' && $main == ''){
    include '../_inc/report.php';
}else
if($brand == 'ABC' && $main == 'TRUE'){
    include '../_inc/analysis.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == ''){
    include '../_inc/report.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == 'TRUE'){
    include '../_inc/analysis.php';
}

答案 2 :(得分:1)

&&的优先级高于||。您当前的代码执行此操作:

if($brand == 'XYZ' || $brand == '123' || ($brand == '1A9' && $main == '')){

此评估为true,因为$brand == 'XYZ'为真。使用括号更正语句:

if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == ''){

有关详细信息,请参阅Operator Precedence

答案 3 :(得分:0)

您遇到运营商优先权问题。试试这个

if($brand == 'ABC' && $main == ''){
    include '../_inc/report.php';
}else
if($brand == 'ABC' && $main == 'TRUE'){
    include '../_inc/analysis.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == ''){
    include '../_inc/report.php';
}else
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == 'TRUE'){
    include '../_inc/analysis.php';
}

答案 4 :(得分:0)

这可以用更短的方式编写:

$include = false;
if($brand=='ABC'){
    if(empty($main))$include = 'report';
    else if($main)$include = 'analysis';
} else if(in_array($brand, array('XYZ', '123', '1A9'))){
    if(empty($main))$include = 'report';
    else if($main)$include = 'analysis';
}
if($include)include '../_inc/'.$include.'.php';