Re: [PHP] Rewind foreach loop



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!
............................................................
.


Quantcast