Jakob
Jakob

Reputation: 2746

How can a boolean expression depend on evaluation order and assignment?

When I evaluate the expressions below, the result is completely different depending on the evaluation order and whether I assign the value or not:

$a = true;
$b = false;
var_dump($a and $b); // false

$c = $a and $b;
var_dump($c); // true

$d = $b and $a;
var_dump($d); // false

I'm completely stumped. Why does this happen?

Upvotes: 1

Views: 215

Answers (2)

Jacob Fike
Jacob Fike

Reputation: 1001

$c = ($a && $b);  // will fix the problem

Upvotes: 1

a1ex07
a1ex07

Reputation: 37382

= has higher priority than and. So $c = $a and $b; is the same as ($c = $a) and $b;, value of $a is assigned to $c. This is different from && which has higher priority than =, so $c = $a && $b evaluates to $c = ($a && $b);

Upvotes: 6

Related Questions