In php the following code throws error:
if($x = 1 && $x == 1)
I’ve been told, it’s because &&
has higher precedence than =
, which cases the expression to get converted to:
if($x = (1 && ($x == 1)))
So far so good, but now consider:
if $x=1; ($x == 1 && $x = 2)
This doesn’t throw error. Why doesn’t it get converted to:
if $x=1; (($x == 1) && $x) = 2)
I’ve been told thats due to =
being right assosiative, but https://www.php.net/manual/en/language.operators.precedence.php says When operators have equal precedence their associativity decides how the operators are grouped.. Here we have =
, &&
and ==
all being of different precedence.
P.S; My actual code is if($result != false && $res = $stmt->get_result())
, which has been copied from some other reputable source, so seems like not using unneeded parenthesis is common in php.