Code:
<?php
$a = 200;
$b = 300;
if ($a > $b $b != 3)
print "Correct";
else
print "Incorrect";
?>
output is: Correct
Can someone help me understand why the output became "Correct"?
CodePudding user response:
To understand what is happening here, you need to look at the list of operator precendence to see what is being evaluated first. It's not left to right. The order of the operators in your if statement are as follows:
- -- ~ (int) (float) (string) (array) (object) (bool) @
- arithmetic (unary and -), increment/decrement, bitwise, type casting and error control< <= > >=
- associative comparison== != === !== <> <=>
- non associative comparison
So in essence, your if statement breaks down to this:
(($a > ($b $b)) != 3)
With your values becomes
((200 > (300 300)) != 3)
((200 > 600) != 3)
(false != 3)
So of course, false is not 3, and makes your if statement correct. If you want to evaluation 200 is greater than 300 AND 300 is not 3
, then you need the logical AND operator, or &&
, which would be
($a > $b && $b != 3)
which would print Incorrect
CodePudding user response:
If-Else
- $a > $b return 0/false
- $b $b return 600
- $b != 3 return 1/true
($a > $b)[false] ($b $b != 3)[true]
False or true return true
Example
if(10==11 || 10!=11){
echo "true";
}else{
echo "false";
}
echo true
I think this is help you for understanding