Geraldo Magalhães Geraldo Magalhães - 6 months ago 32
PHP Question

PHP - simple condition with parenthesis

I have a stupid question about this condition.

Why when I put parenthesis, the result of the condition changes?

$std = new \stdClass();
$std->bool = false;
$resultCond1 = isset($std->bool) and $std->bool == true;
$resultCond2 = (isset($std->bool) and $std->bool == true);

var_dump($resultCond1); // True.
var_dump($resultCond2); // False.


I believe this is due to operator precedence.

Notice in that table that the assignment operators lie firmly between and and &&. Here's what I think is happening:

In the first example, isset is returning true and, prior to the and operation taking place the assignment is happening. After the assignment, the result of the assignment is and'ed and the result of that and operation is then summarily discarded.

In the second example the parentheses dictate that the assignment happens last and so you get the expected result.

You can see this more clearly if you remove the assignment operation altogether and just dump the result of the operations themselves:

var_dump(isset($std->bool) and $std->bool == true);   // bool(false)
var_dump((isset($std->bool) and $std->bool == true)); // bool(false)