0

I came across this part of code somewhere and I don’t understand how both operations evaluate to 3

<?php
$x = 1;
$y = $x + $x++;
var_dump($y); // output : 3

$x = 1;
$y = $x + $x + $x++;
var_dump($y); // output : 3

what's going on? what am I missing?

Abdelaziz Dabebi
  • 1,624
  • 1
  • 16
  • 21
  • possible duplicate of [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) –  Jul 26 '15 at 00:50
  • Seriously? downvote? I found a code I didn't understand so I came here to ask about. Thanks! – Abdelaziz Dabebi Jul 26 '15 at 00:55
  • @AzizFCB If votes really bother you, just open up your browser console and change it, just don't reload the page anymore, *really don't* :) – Rizier123 Jul 26 '15 at 00:57
  • 1
    tends to show up as a question asked in exams\job interviews to test knowledge. –  Jul 26 '15 at 00:57

1 Answers1

4

As many times the PHP manual holds also the answer for this:

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

<?php

    $a = 1;
    echo $a + $a++; // may print either 2 or 3

    $i = 1;
    $array[$i] = $i++; // may set either index 1 or 2

So as you can see maybe someone will get 2 first and not 3, since the order is not specified. That's all there is to it.

Rizier123
  • 58,877
  • 16
  • 101
  • 156