Re: Rewind foreach loop

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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:
 > 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?

 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 ----------------+

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux