Re: [PHP] Rewind foreach loop
- From: robert@xxxxxxxxxxxxx (Robert Cummings)
- Date: Fri, 30 Nov 2007 14:46:57 -0500
On Fri, 2007-11-30 at 09:51 -0800, Jim Lucas wrote:
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 is dangerous use of the array functions. A problem occurs when you
have a value that evaluates to false (such as the first entry in the
example array :). In fact the only way to ensure you traverse the array
properly is to use each() since it returns an array except when no more
entries exist. Also you want to reset() the array before looping
(normally anyways).
<?php
reset( $data );
while( ($entry = each( $data )) )
{
// ...
if( $errorCondition )
{
prev( $data );
continue;
}
next( $data );
}
?>
Cheers,
Rob.
--
............................................................
SwarmBuy.com - http://www.swarmbuy.com
Leveraging the buying power of the masses!
............................................................
.
- Follow-Ups:
- Re: [PHP] Rewind foreach loop
- From: Robert Cummings
- Re: [PHP] Rewind foreach loop
- References:
- Rewind foreach loop
- From: Jeffery Fernandez
- Re: [PHP] Rewind foreach loop
- From: Jim Lucas
- Rewind foreach loop
- Prev by Date: Re: newbie question on escaping strings
- 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):