Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to move array pointer inside foreach loop?

Tags:

php

$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   var_dump($animal);
   next($animals);
}

The code above outputs: cat, dog, horse, elephant. I thought the next function should move the internal pointer of $animals and, thus, I should be getting this output instead: cat, horse.

How do I make the internal pointer of $animals move forward (and backwards) such that it is affected in the foreach?

EDIT 1:

From the manual:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

Nonetheless, I think this is what I need to do.

EDIT 2:

Per "Your Common Sense"'s link, I will provide a more detailed explanation of my problem. Here's some psuedo code:

array $foos;

start loop of $foos
 - do thing #1
 - do thing #2
 - do thing #3
 - keep doing thing #3 while the current value of $foos in the loop meets a certain criteria
loop

When execution returns to the start of the loop, it should continue from the last array accessed by #3. Note that the array is associative, thus a for ($i = 0 ... approach won't work.

like image 874
StackOverflowNewbie Avatar asked May 05 '12 04:05

StackOverflowNewbie


1 Answers

You can just create an ArrayIterator­Docs which is seekable­Docs.

As it is an iterator, you can change the position while you iterate over it, some rudimentary example:

foreach ($iterator as $current) {
    $iterator->next();
}

It should offer everything you need out of the box. If not, you could encapsulate your needs into an Iterator­Docs on your own as well.

like image 50
hakre Avatar answered Sep 23 '22 21:09

hakre