7

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.

3
  • I could point that is similary to this var_dump((int)((0.1 + 0.7) * 10));//int(7) (a float precision problem) . But I really don't know. Commented Dec 12, 2016 at 19:39
  • See also 3v4l.org/3bWI0 Commented Dec 12, 2016 at 19:54
  • 1
    This is explained here: gist.github.com/nikic/6699370 There's probably also one or ten duplicates on SO. Commented Dec 12, 2016 at 20:29

1 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

1 Comment

is this a bug or feature? it does happens in javascript too var a = 1; var c = a + a++; console.log(c); var a = 1; var c = a + a + a++; console.log(c);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.