I have the following code:
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';
}
Information is passed to the PHP page within the URL, such as:
?br=ABC&cr=MAY2014&pd=NOV2013&mn=TRUE
?br=XYZ&cr=MAY2014&pd=NOV2013&mn=TRUE
And handled as follows:
$brand = $_GET['br'];
$main = $_GET['mn'];
What is happening is that if $brand = ABC and $main = TRUE
then the analysis.php
is loaded successfully (which is correct).
However, if $brand = XYZ and $main = TRUE
then report.php
is loaded, which is not the behaviour I expect or need.
Is this connected with the way the operators work or is my code incorrect. Any help and feedback welcomed.
&&
has higher precedence than ||
. Your current code does this:
if($brand == 'XYZ' || $brand == '123' || ($brand == '1A9' && $main == '')){
This evaluates to true, because $brand == 'XYZ'
is true. Use parentheses to correct the statement:
if(($brand == 'XYZ' || $brand == '123' || $brand == '1A9') && $main == ''){
See Operator Precedence for more details.
You should write conditions with proper brckets.
Try below code
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';
}
Try this
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';
}
You have problem with operator precedence. Try this
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';
}
This can be written in a much shorter way:
$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';