Re: Rewind foreach loop
- From: ZeldorBlat <zeldorblat@xxxxxxxxx>
- Date: Thu, 29 Nov 2007 19:15:44 -0800 (PST)
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;
}
.
- References:
- Rewind foreach loop
- From: Jeffery Fernandez
- Rewind foreach loop
- Prev by Date: Re: [PHP] Rewind foreach loop
- Next by Date: Re: [PHP] Rewind foreach loop
- Previous by thread: Re: [PHP] Rewind foreach loop
- Next by thread: Re: [PHP] Rewind foreach loop
- Index(es):
Relevant Pages
|
|