3

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.

3
  • You'd need $cur = current($arr['key']['name']); if you're doing next($arr['key']['name']);. Commented Apr 10, 2012 at 4:53
  • Because then I would get the current element of $arr['key']['name'] instead of a the current element of $arr which is $arr['key'] :) Commented Apr 10, 2012 at 4:57
  • This seems like something undocumented/bug. I rewrote "$cur = current($arr);" to "current($arr);" and the loop ended all right. Or I replaced "$arr['key']['name']" with "$arr['name']" and the loop ended all right. Commented Oct 14, 2013 at 15:53

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How come? It doesn't make sense and it isn't mentioned anywhere in the current()'s manual.
Probably because no one ever expected it to be used this way.
Yes but if it really does reset the pointer for the nested arrays, why doesn't it do so on every iteration when current() runs but only after the whole $arr['key']['name'] array has been traversed?
2

Why don't you do it this way ?

Code :

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

}

1 Comment

Because I don't need to access all the elements at one run, I just made that small example to demonstrate the problem, in my real code it is not a loop :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.