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();
}
8
  • 3
    Not using foreach when using iterators seems so like PHP3... ;) Commented Oct 3, 2012 at 13:35
  • Yeah, but I must know about next element. Commented Oct 3, 2012 at 13:36
  • Anyway shame that I forget about next() :P Commented Oct 3, 2012 at 13:39
  • You should use foreach. Better performance than while. Less error prone, like you demonstrated. Commented Oct 3, 2012 at 13:43
  • @Sven - Do you have any benchmarks for the better performance you claim? Commented Oct 3, 2012 at 13:53

4 Answers 4

7

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

while ($it->valid()) {
    ...
    $it->next();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just Curios .. did you test this code ??? .. You would know it has errors if you did
@Baba - No, I just added the $it->next() -- because that's the cause of the problem. What errors do you mean?
Just edited your code with proper formatting .. you can see the diffence
3

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

Comments

2

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

Comments

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

Comments

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.