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
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php