Assessment of a non-intuitive expression with increment

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 got this result:

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

I was expecting 1,2,3,4,5, not 1,3,3,4,5. Why after $a=1; $b=$a+$a++; $a=1; $b=$a+$a++; get $b=3 ?

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

+46
increment php opcode
Sep 05 '17 at 12:11
source share
3 answers
 $a=1; $b=$a+$a++; var_dump($b); // int(3) 

You suggested that the above expression evaluates from left to right as follows (the 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 sub-expressions will be evaluated in this order . The PHP operators documentation page says (emphasis mine):

Operator precedence and associativity only determine how expressions are grouped; they do not determine the order of evaluation. In PHP, there is no (in the general case) specifying in which order the expression is evaluated , and code that assumes a certain evaluation order should be avoided, because the behavior may vary between versions of PHP or depending on the surrounding code.

It is only by chance that the values โ€‹โ€‹computed by PHP for other expressions correspond to the values โ€‹โ€‹that you assumed. Their values โ€‹โ€‹may differ if the code is executed using a different version of the PHP interpreter.

+30
Sep 05 '17 at 12:43 on
source share

In PHP, there is no (in general case) indicating in what order the expression is evaluated, and code that involves a certain evaluation order should be avoided [..]

http://php.net/manual/en/language.operators.precedence.php

The reason you get different results is because the right and sometimes the left operands are sometimes evaluated first. PHP makes no guarantees regarding the order of operations, so there is no right answer, and this directly relates to the undefined category .

+23
Sep 05 '17 at 12:23
source share

According to PHP manual

The priority and associativity of operators determine only how the expressions are grouped, they do not determine the order of evaluation. PHP should not (in general) indicate in what order the evaluation expression and the code, which suggests a certain evaluation order, should be avoided, as the behavior may vary between versions of PHP or depending on the surrounding code.

 <?php $a = 1; echo $a + $a++; // may print either 2 or 3 $i = 1; $array[$i] = $i++; // may set either index 1 or 2 ?> 

The strange thing is that I expected other lines like $b=$a+$a+$a++; will follow the same pattern, but itโ€™s not.

+10
Sep 05 '17 at 12:25
source share



All Articles