Why does PHP keep resetting the array pointer?

So, I spent 2 hours trying to figure this out, minifying the code as much as possible to isolate the problem, but I can't figure it 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);

      

It's an endless loop. For some reason, after going through all the values ​​of $ arr ['key'] ['name'], key () returns to 0 instead of returning NULL. Removing $ cur = current ($ arr); however solves this problem. According to php manual , current()

doesn't affect array pointer at all. Now I know that copying the array would reset its pointer, but there is no copying, and if $ k existed it would always be null, not going from 0 to 2 and then resetting back to 0.

+3


source to share


2 answers


current()

does not move the array pointer for the array you are using, but you are using it on different arrays. This is a pointer reset for nested arrays.



+4


source


Why don't you do it like this?

Code:



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

}

      

+2


source







All Articles