6
$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.

2
  • 3
    this is not an explanation of the real life task but the same xy problem. WHY do you need that? Commented May 5, 2012 at 4:47
  • 2
    There is probably a cleaner design hidden somewhere in this implementation detail concern Commented May 5, 2012 at 4:51

6 Answers 6

10

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.

8

You shouldn't mix foreach with direct pointer access. If you want to move around in the array, just replace the foreach with a C-style for. It's wordier at the top, but works with an identical loop body to the foreach case, with the difference being that you can muck with the internal pointer and have the desired result.

$animals = array('cat', 'dog', 'horse', 'elephant');
for ($animal = current($animals), $index = key($animals); 
       $animal; 
       $animal = next($animals), $index = key($animals)) {
  print "$index:";
  var_dump($animal);
  next($animals);
} 

Output:

0:string(3) "cat"
2:string(5) "horse"

It's very misleading to use a straight-through iteration construct like foreach when you're actually moving around back and forth within the array. The above for loop is better in this regard, but not by much; a while loop, with all the details explicitly spelled out in the loop body, might be the best choice.

4
  • Mark, I've updated the original question to explain a bit better what I am trying to do. Hope it helps. Commented May 5, 2012 at 4:42
  • The above for() loop behaves exactly like a foreach() loop over an array. If you're doing as $key => $value, then you just need to add a call to key as well, which I have now done.
    – Mark Reed
    Commented May 5, 2012 at 4:45
  • I'm a bit confused by the 2nd parameter in your for-loop. Is that even valid syntax? Commented May 5, 2012 at 4:53
  • It's valid - the code works as written. What's your question? We can chat if you like.
    – Mark Reed
    Commented May 5, 2012 at 5:00
6

Mark's solution is pretty close but fails if the array contains values like 0, false or "" which evaluate false in the second for loop expression.

This solution works for all arrays and is a bit closer to the "spirit" of a for loop. The reset() in the first loop expression ensures we start at the beginning of the array which would be the case with foreach. The second expression in the for loop needs to evaluate if the element the array pointer points to exists. key() returns null if the array pointer points beyond the end of the array or the array is empty. The third expression advances the array pointer at the end of each iteration.

$animals = array('cat', 'dog', 'horse', 'elephant');
for (reset($animals); key($animals) !== null; next($animals)) {
    $animal = current($animals);
    var_dump($animal);
    next($animals);
}

This outputs:

string(3) "cat"
string(5) "horse"
1
  • It actually looks like a for loop, can be used in lots of situations, and solves the problem. Thank you.
    – Noumenon
    Commented Feb 2, 2013 at 16:33
1

Add & to value

foreach ($variable as $key => &$value) {

}

Now $value reference to $variable[$key] address

1
  • This is very usefull when you want to update the values of the array when you do a foreach loop. The other way would be to reference it in a for loop with something like $variable[$key] = 'MyNewValue';
    – Nebulosar
    Commented Nov 13, 2019 at 8:57
0

I think cause he just wants to skip elements, he could use 'continue' combined with an if-clause inside the foreach.

$skip=array ('dog', 'elephant');
$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   if (in_array($animal, $skip)) {
       continue;
   }
   var_dump($animal);
}

this will output:

string(3) "cat" 
string(5) "horse"

Variante 2 without continue with the same effect:

$skip=array ('dog', 'elephant');
$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   if (!in_array($animal, $skip)) {
        var_dump($animal);
   }

}
-1

You don't need to increment the pointer manually at the end of a foreach loop - it's done automatically. You don't need anything more than:

foreach($animals as $animal) {
    var_dump($animal)
}
3
  • OP is trying to skip elements, @andrewsi.
    – Mark Reed
    Commented May 5, 2012 at 4:41
  • I know, but I really want to advance the pointer to the next item. Refer to the example output I am expecting in the original post. Commented May 5, 2012 at 4:41
  • 4
    Memo to self: stackoverflow and insomnia do not mix
    – andrewsi
    Commented May 5, 2012 at 4:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.