Re: Rewind foreach loop
| From: | Steve Edberg | Date: | Fri, 30 Nov 2007 03:38:59 +0000 |
| Subject: | Re: Rewind foreach loop | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-265282@lists.php.net to get a copy of this message | ||
At 2:11 PM +1100 11/30/07, Jeffery Fernandez wrote:
On Fri, 30 Nov 2007 02:01:47 pm Chris <dmagick@gmail.com> wrote: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@ucdavis.edu | | Bioinformatics programming/database/sysadmin (530)754-9127 | +---------------- said t e lawrence, picking up his fork ----------------+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); }} 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 "Value: $value" . PHP_EOL;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.