Re: Rewind foreach loop



On Nov 29, 9:55 pm, jeff...@xxxxxxxxxx (Jeffery Fernandez) wrote:
Hi all,

Is it possible to rewind a foreach loop? eg:

$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index => $value)
{
if ($value == 5)
{
prev($numbers);
}
echo "Value: $value" . PHP_EOL;

}

The above doesn't seem to work. In one of my scenarios, when I encounter and
error in a foreach loop, I need the ability to rewind the array pointer by
one. How can I achieve this?

regards,
Jeffery

There's a note in the manual about foreach:

Note: Unless the array is referenced, foreach operates on a copy of
the specified array and not the array itself. foreach has some side
effects on the array pointer. Don't rely on the array pointer during
or after the foreach without resetting it.

So, according to the first part you can try this:

foreach (&$numbers as $index => $value)
{
if ($value == 5)
{
prev($numbers);
}
echo "Value: $value" . PHP_EOL;
}

Note the & in front of $numbers.

According to the second part of the note, however, that doesn't
necessarily provide the desired effect.

Another way would be to use a while loop with each(). Something like
this should work:

while (list($index, $value) = each($numbers))
{
if ($value == 5)
{
prev($numbers);
}
echo "Value: $value" . PHP_EOL;
}
.



Relevant Pages

  • Re: [PHP] Rewind foreach loop
    ... Is it possible to rewind a foreach loop? ... to rewind the array pointer and continue with the loop. ... Victoria - 3136 ...
    (php.general)
  • Re: [PHP] Rewind foreach loop
    ... > and error in a foreach loop, I need the ability to rewind the array ... rewind the array pointer and continue with the loop. ... I would think that if you rewound the array pointer as above, you'd simply end up in an infinite loop, as you'd keep hitting the condition that triggered the rewind. ...
    (php.general)
  • Re: [PHP] Rewind foreach loop
    ... 30 Nov 2007 02:01:47 pm Chris wrote: ... Is it possible to rewind a foreach loop? ... rewind the array pointer and continue with the loop. ...
    (php.general)
  • Re: [PHP] Rewind foreach loop
    ... Is it possible to rewind a foreach loop? ... rewind the array pointer and continue with the loop. ...
    (php.general)
  • Re: regexp problem in program
    ... This disables certain unsafe practices. ... 'while' is normally used for this purpose instead of 'foreach'. ... > # the leading whitespaces, ... > # is to use another foreach loop to substitute a comma for white- ...
    (comp.lang.perl.misc)