This evaluates to TRUE.
$A = TRUE;
$B = FALSE;
$result = ($A) AND ($B) ? true : false;
Why is the evaluation giving true, and how exactly is the evaluation done step by step?
Thanks
It's not related to the ternary. It's because =
has a higher precedence than and
. That means you're setting $result = ($A)
and then everything after the and
is irrelevant.
($B) ? true : false
does evaluate to false
, but because the assignment already happened in the first part of the expression, it's not assigned to anything. It's basically ignored.
For a more straightforward example, try
$result = true and false;
$result
will be true
.
My Initial thought was It's returning true
because of missing parenthesis. Reason: ternary expressions are evaluated from left to right. See DEMO it'll return bool(false)
if you wrap it with parenthesis ()
$A = TRUE;
$B = FALSE;
$result = (($A) AND ($B)) ? true : false;
var_dump($result);
Edited: Why & how the second FALSE is being used?
Because and/or
have lower priority than =
, but the ||
or &&
have higher priority than =
. For example.
<?php
$bool = true && false;
var_dump($bool); // false, that's expected
$bool = true and false;
var_dump($bool); // true, ouch!
?>
Hope it is clear now :). source: http://php.net/manual/en/language.operators.precedence.php#117390