define.cc
define.cc

Reputation: 71

About logical operator && in php

here is the code

$a = 2;
$a && $a = 1;

var_dump( $a ); // result 1

Why $a is 1?

According to the document, logical operator '&&' has greater precedence than assign operator, it should be interpreted as ($a && $a) = 1, then there should be a syntax error.

Upvotes: 1

Views: 93

Answers (3)

usoban
usoban

Reputation: 5478

$a && $a = 1;

is an expression of boolean type. Since $a is truthy, the evaluation of the expression continues onto the second part, which is the assignment. As a side effect of the assignment, $a now holds 1.

If $a had been 0 in the start, it'd remain 0 in the end, as the evaluation of the expression'd be terminated right after testing the first condition.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

From the documentation

Note:
Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

The documentation doesn't specify what rules are followed at this point, but we can infer that your code is equivalent to this:

$a && ($a = 1)

Because && is "lazy" in that it won't bother evaluating further arguments if it finds one that's false, this means that $a will only be set to 1 if it previously held a truthy value (in your case, 2 is truthy). If you had set $a = 0 then it would have stayed 0.

Upvotes: 5

Machavity
Machavity

Reputation: 31654

The way it's written, you're saying the same thing as this

$a = 2;
if($a) $a = 1;

Since 2 is something, it succeeds and changes $a to 1.

So why does it do this? You have a statement that $a = 2; There's no order of operations here so PHP processes it. The order of operations DOES come into effect on the second statement. Remember, $a is SOMETHING, (i.e. truthy). Let's change your code slightly

$a = 0;
$a && $a = 1;
echo $a;

As you can see, $a is now falsy. So the order prevents the script from changing the value and the script outputs 0

Upvotes: 2

Related Questions