Re: [PHP] Rewind foreach loop
- From: sbedberg@xxxxxxxxxxx (Steve Edberg)
- Date: Thu, 29 Nov 2007 19:38:59 -0800
At 2:11 PM +1100 11/30/07, Jeffery Fernandez wrote:
On Fri, 30 Nov 2007 02:01:47 pm Chris <dmagick@xxxxxxxxx> wrote:Jeffery Fernandez wrote:> > echo "Value: $value" . PHP_EOL;
> 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);
> }
> }
>
> 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?
echo $numbers[$index-1] . PHP_EOL;
That will only give me the value of the previous index. What I want is to
rewind the array pointer and continue with the loop.
I would think that if you rewound the array pointer as above, you'd simply end up in an infinite loop, as you'd keep hitting the condition that triggered the rewind. So I'm assuming you have some other test in there and this is just a stripped down example.
If you're using a one-dimensional array, as opposed to a multidimensional and/or associative array, you can do (untested):
$Count = count($numbers);
for ($i=0; $i<$Count; $i++) {
$value = $numbers[$i];
if ($value == 5 && some_other_test()) {
$value = $numbers[--$i];
}
echo "Value: $value" . PHP_EOL;
}
Wouldn't be much more complex to extend to a multidimensional array with an integer index. If you were using an associative array with a string index, you'd probably have to do something like
$NotJustNumbers = array('a'=>'slurm', 'b'=>'fry', 'c'=>'leela');
$Keys = array_keys($NotJustNumbers);
$Count = count($Keys);
for ($i=0; $i<$Count; $i++) {
$value = $NotJustNumbers[$Keys[$i]];
if ($value == 5 && some_other_test()) {
$value = $NotJustNumbers[$Keys[--$i]];
}
echo "Value: $value" . PHP_EOL;
}
- steve
--
+--------------- my people are the people of the dessert, ---------------+
| Steve Edberg http://pgfsun.ucdavis.edu/ |
| UC Davis Genome Center sbedberg@xxxxxxxxxxx |
| Bioinformatics programming/database/sysadmin (530)754-9127 |
+---------------- said t e lawrence, picking up his fork ----------------+
.
- References:
- Rewind foreach loop
- From: Jeffery Fernandez
- Re: [PHP] Rewind foreach loop
- From: Chris
- Re: [PHP] Rewind foreach loop
- From: Jeffery Fernandez
- Rewind foreach loop
- Prev by Date: Re: [PHP] Rewind foreach loop
- Next by Date: Re: [PHP] Rewind foreach loop
- Previous by thread: Re: [PHP] Rewind foreach loop
- Next by thread: Re: Rewind foreach loop
- Index(es):
Relevant Pages
|