Home » Php » Why does negation happen last in an assignment expression in PHP?

Why does negation happen last in an assignment expression in PHP?

Posted by: admin November 30, 2017 Leave a comment


The negation operator has higher precedence than the assignment operator, why is it lower in an expression?


if (!$var = getVar()) {

In the previous expression the assignment happens first, the negation later. Shouldn’t the negation be first, then the assignment?


The left hand side of = has to be a variable. $var is a variable, whereas !$var is not (it’s an expr_without_variable).

Thus PHP parses the expression in the only possible way, namely as !($var = getVar()). Precedence never comes to play here.

An example of where the the precedence of = is relevant is this:

$a = $b || $c // ==> $a = ($b || $c), because || has higher precedence than =
$a = $b or $c // ==> ($a = $b) or $c, because or has lower precedence than =


In short, assignments will always have precedence over their left part
(as it would result in a parse error in the contrary case).

 $b=12 + $a = 5 + 6;
 echo "$a $b\n";
 --> 11 23

 $b=(12 + $a) = (5 + 6);
 echo "$a $b\n";
 --> Parse error

The PHP documentation has now a note concerning this question: http://php.net/manual/en/language.operators.precedence.php
(i guessed it was added after your question)

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


Negotiation operator needs to check a single value at the next, so if you give like this

!$var =

the operator onlyapplicable for the next variable so !$var is will seperated. so only we need to give

!($var =