Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unintuitive expression evaluation with incrementation

For the following code

<?php  $a=1;   $b=$a++;              var_dump($b); $a=1;   $b=$a+$a++;           var_dump($b); $a=1;   $b=$a+$a+$a++;        var_dump($b); $a=1;   $b=$a+$a+$a+$a++;     var_dump($b); $a=1;   $b=$a+$a+$a+$a+$a++;  var_dump($b); 

I obtained this result:

int(1) int(3) int(3) int(4) int(5) 

I expected 1,2,3,4,5 rather than 1,3,3,4,5. Why after $a=1; $b=$a+$a++; we obtain $b=3?

PHP 7.1.5-1+deb.sury.org~xenial+1 (cli) (built: May 11 2017 14:07:52) ( NTS )

like image 855
Daniel Avatar asked Sep 05 '17 12:09

Daniel


1 Answers

$a=1;   $b=$a+$a++;           var_dump($b);            // int(3) 

You assumed that the expression above is evaluated from left to right as follows (temporary variables $u and $v are introduced in the explanation for clarity):

 $a = 1;  $u = $a;              //    ($a)   the LHS operand of `+`  $v = $a;              //  \ ($a++) the RHS operand of `+`  $a ++;                //  /  $b = $u + $v;         // 2 (1+1) 

But there is no guarantee that the subexpressions are evaluated in a specified order. The documentation page of the PHP operators states (the emphasis is mine):

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.

Only by chance the values computed by PHP for the other expressions match the values you assumed. Their values might be different when the code is executed using a different version of the PHP interpreter.

like image 95
axiac Avatar answered Oct 07 '22 01:10

axiac