Page 1 of 1

foreach loop and each() function

Posted: Sun Sep 19, 2010 11:28 am
by uk1simon
Hiy,

I'm a php newbie and just learning about loops.
Ive just come across a problem, by accident, I think.
This is a piece of code:

Code: Select all

<?php

$prices = array('door' => 10, 'handle' => 20, 'frame' => 30);

while ($element = each($prices)) {
	echo $element['key'];
	echo ": ";
	echo $element['value'];
	echo "<br />";
}

echo "<br />";
foreach ($prices as $key => $value) {
	echo $key . ": " . $value . "<br />";
}

echo "<br />";
while ($element = each($prices)) {
	echo $element['key'];
	echo ": ";
	echo $element['value'];
	echo "<br />";
}

?>
The 3 loops do exactly the same thing however the third loop doesn't work for some reason. I think that foreach loop changes something but I don't know. What is the problem?


Regards,
Simon

Re: foreach loop and each() function

Posted: Sun Sep 19, 2010 11:38 am
by uk1simon
Alright I've found a solution.
I need to use reset() function.


Thanks,
Simon