The internal pointer of an array
I discovered recently that if you walk through an array using array_walk or array_walk_recursive, then the array’s internal pointer is left at the end of the array. Clearly this isn’t something that I’ve needed to know before!
This code example shows the fundamentals:
$var = [ 'a' => 'a', 'b' => 'b', ]; array_walk($var, function ($value) { }); var_dump(key($var));
The output is NULL and you use reset() to put the internal pointed back to the start.
Foreach is different in PHP 7!
Note that foreach works the same way in PHP 5, but works differently in PHP 7:
$var = [ 'a' => 'a', 'b' => 'b', ]; foreach ($var as $value) { } var_dump(key($var));
will output string(1) "a" on PHP 7 and NULL on PHP 5.
Thanks for pointing out the behaviour of foreach in PHP 7! These are the kind of changes I really fear when moving to the next major version :-)
Thanks for the info.
As reported in the "Migrating from PHP 5.6.x to PHP 7.0.x > Backward incompatible changes":
foreach no longer changes the internal array pointer
http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach.array-pointer
Also to note:
foreach by-value operates on a copy of the array