Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing array access expression with no key

Tags:

php

Why is this ok in PHP (7.3)? Is there any use case for it?

<?php

$foo =  [10, 20, 30];
echo $foo[]++, "\n", ++$foo[], "\n", ++$foo[], "\n";

outputs:

php test.php

1
1

I expected a read error like below.

<?php

$foo = [10, 20, 30];
$foo[] += 1; // No error either
$foo[] = $foo[] + 1; //PHP Fatal error:  Cannot use [] for reading in
like image 532
bmewburn Avatar asked Jan 24 '26 01:01

bmewburn


1 Answers

$foo[]++ first creates a new, null entry in $foo, which is echo'ed, resulting in a a blank line (since echo null; outputs nothing). The new entry in $foo is then incremented, so null is type juggled to 0 as an integer, resulting in a value 1.

++$foo[] creates another new, null entry in $foo, which in this case is incremented before being output, hence the two lines with 1 in them.

If you change your code to use var_dump instead of echo you can see this more clearly:

$foo =  [10, 20, 30];
var_dump($foo[]++);
var_dump(++$foo[]);
var_dump(++$foo[]);
var_dump($foo);

Output:

NULL
int(1)
int(1)
array(6) {
  [0]=>
  int(10)
  [1]=>
  int(20)
  [2]=>
  int(30)
  [3]=>
  int(1)
  [4]=>
  int(1)
  [5]=>
  int(1)
}

Demo on 3v4l.org

Note that unlike incrementing null, which results in 1, decrementing null has no effect (var_dump(--$foo[]) outputs null). This behaviour is described in the manual.

like image 82
Nick Avatar answered Jan 25 '26 16:01

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!