Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP keeps resetting the array pointer?

Tags:

arrays

php

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.

like image 813
John Avatar asked May 17 '26 11:05

John


1 Answers

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.

like image 77
Ignacio Vazquez-Abrams Avatar answered May 20 '26 01:05

Ignacio Vazquez-Abrams