Pragmatism in the real world

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.

3 thoughts on “The internal pointer of an array

  1. 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 :-)

Comments are closed.