Can anybody explain why these 2 produce the same result?
$a = 1;
$c = $a + $a++;
var_dump($c);//int(3)
and
$a = 1;
$c = $a + $a + $a++;
var_dump($c);//int(3)
Tested in PHP 7.1. Reviewed Opcode dumps for both cases but still cant get the point. If we add more $a vars to the expression, it produces the expected result.
From PHP: Operator Precedence:
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Example #2 Undefined order of evaluation
$a = 1; echo $a + $a++; // may print either 2 or 3 $i = 1; $array[$i] = $i++; // may set either index 1 or 2
So in your first example, PHP is obviously returning 1
for $a++
then incrementing it to 2
and then adding the new $a
, which is 2
.
In your second example, PHP is returning 1
for $a
then adding $a
then adding $a
and then incrementing it to 2
.
As can be seen here: https://3v4l.org/kvrTr:
PHP 5.1.0 - 7.1.0
int(3)
int(3)
PHP 4.3.0 - 5.0.5
int(2)
int(3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With