3

Array in my code is quite big so I pasting it in pastebin. http://pastebin.com/6tviT2Xj

I don't understand why I am getting endless loop

Logic of this script is:

$it = new ArrayIterator($options);
while($it->valid()) {
    print $it->key();
    print $it->current();
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Codium
  • 3,200
  • 6
  • 34
  • 60

4 Answers4

7

Because you never move in you iterator (with ArrayIterator::next()).

while ($it->valid()) {
    ...
    $it->next();
}
Björn
  • 29,019
  • 9
  • 65
  • 81
  • Just Curios .. did you test this code ??? .. You would know it has errors if you did – Baba Oct 03 '12 at 13:38
  • @Baba - No, I just added the `$it->next()` -- because that's the cause of the problem. What errors do you mean? – Björn Oct 03 '12 at 13:40
  • Just edited your code with proper formatting .. you can see the diffence – Baba Oct 03 '12 at 13:41
3

you should use $it->next(); else you will cicle over the same key eternally

kawashita86
  • 1,555
  • 3
  • 18
  • 25
2

you're iterating over current element, you need to do $it->next(); to point/go to the next element

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
1

The main issue is not using $it->next(); in your but that still many not give you the desired output because If you run print $it->current(); it would only return Array since you can not output array information with print.

You should be using RecursiveArrayIterator and RecursiveIteratorIterator since you are dealing with multidimensional array

To get all values try :

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($options));
foreach ( $it as $key => $val ) {
    echo $key . ":" . $val . "\n";
}

See full demo : http://codepad.viper-7.com/UqF18q

Baba
  • 94,024
  • 28
  • 166
  • 217