Re: Rewind foreach loop
| From: | Jim Lucas | Date: | Fri, 30 Nov 2007 17:51:00 +0000 |
| Subject: | Re: Rewind foreach loop | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-265304@lists.php.net to get a copy of this message | ||
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