Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator and assignment at the same time in PHP?

Tags:

php

In this statement:

1 + $newVar = 200;

$newVar gets created and assigned the value of 200. How does this work? Precedence rules show that the addition takes place first, before the assignment. I can't wrap my head around this. How does the assignment take place if the variable is evaluated with the + operator first?

PHP provides this little nugget. Does this mean these rules apply except when they don't?

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.

like image 870
Evil Elf Avatar asked May 11 '18 19:05

Evil Elf


1 Answers

In this instance, it would not make sense for PHP to evaluate the arithmetic expression before the assignment, as arithmetic operator returns a value and you can't assign a value to a value. So it seems like PHP breaks its rules a bit in this case and does the assignment first.

Some code to show assignment is taking place first:

$nVar = 0;
echo (1 + $nVar = 200);     //201
echo $nVar;    //200

If the + occurred first (and somehow was legal and made sense), they would both echo 200, because (1 + $nVar) does not set $nVar to 1, and you would get the result of the assignment.

Check out this example as well:

$nVar = true;
echo (!$nVar = false);  // true | 1
echo '<br/>br<br/>';
var_dump($nVar);        // false

! has higher precedence and is also right associative, yet assignment still evaluates first.

like image 84
Nick Rolando Avatar answered Sep 29 '22 17:09

Nick Rolando