John
John

Reputation: 908

Why PHP keeps resetting the array pointer?

So I spent 2 hours trying to figure this out, minimizing the code as much as possible to isolate the problem, yet I can't figure this out.

So I have this code:

$arr['key']['name'] = array("one", "two", "three");

$counter = 0;
do
{
    $cur = current($arr);

    $k = key($arr['key']['name']);
    next($arr['key']['name']);
}while($k !== null);

This is a never ending loop. For some reason, after going through all the $arr['key']['name'] values, key() instead of returning NULL, goes back to 0 again. Removing $cur = current($arr); however solves that problem. According to php manual, current() doesn't affect the array pointer at all. Now I know that copying an array will reset its pointer but there's no copying going on and if there was $k would constantly be zero instead of going from 0 to 2 and then resetting back to 0.

Upvotes: 3

Views: 270

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798754

current() doesn't move the array pointer for the array you use it on, but you're using it on different arrays. It is resetting the pointer for the nested arrays.

Upvotes: 4

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Why don't you do it this way ?

Code :

foreach ($arr['key']['name'] as $k)
{
    // do something with $k

}

Upvotes: 2

Related Questions