Re: [PHP] Rewind foreach loop
- From: lists@xxxxxxxxx (Jim Lucas)
- Date: Fri, 30 Nov 2007 09:51:00 -0800
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
No, you can't rewind the array. Foreach makes a copy of the array, and works off that copy.
You might need to look into using do...while() instead
Something thing like this should work.
<?php
$row = current($your_array); Gives you the first element in $your_array
do {
....
work with your $row...
determine if their is an error
....
if ( $error ) {
# Watch out for infinite loop....
# maybe have a counter that increments each time it rewinds $your_array
# and have it stop at 10 loops or something.
prev($your_array);
}
} while( $row = next($your_array) );
?>
This way, you are working on the only copy of $your_array
--
Jim Lucas
"Some men are born to greatness, some achieve greatness,
and some have greatness thrust upon them."
Twelfth Night, Act II, Scene V
by William Shakespeare
.
- Follow-Ups:
- Re: [PHP] Rewind foreach loop
- From: Robert Cummings
- Re: [PHP] Rewind foreach loop
- References:
- Rewind foreach loop
- From: Jeffery Fernandez
- Rewind foreach loop
- Prev by Date: <JOB OPPORTUNITY>
- Next by Date: Re: [PHP] Join question
- Previous by thread: Re: [PHP] Rewind foreach loop
- Next by thread: Re: [PHP] Rewind foreach loop
- Index(es):