Search code examples
phpphp-7php-7.2post-increment

Explaining arrays and ++ operator on index and value


I was studying operators priority in php7.2 when I executed this code :

$i = 1;
$a[$i] = $i++;

var_dump($a);

$j = 1;
$b[$j++] = $j++;

var_dump($b);

And I get this result :

array(1) {
  [2]=>
  int(1)
}
array(1) {
  [1]=>
  int(2)
}

I don't understand why this code give these outputs. I could get the first var_dump but the second seems really weird to me.

Could you explain how this two examples are interpreted by php step by step ?

I don't get the same results on php 4 though.


Solution

  • Even if C++ is a compile time language, there is no standard behaviour on instructios like x = x++ and the result differs between compilers.

    PHP is runtime precompiled and thus optimized on performance with regard of compilation time and execution time as well. The behaviour is undefined and may differ from version to version.

    You should never rely on thus constructs within one instruction - in no language, except it was well defined in its specs.