foreach loop and each() function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
uk1simon
Forum Newbie
Posts: 2
Joined: Sun Sep 19, 2010 11:16 am

foreach loop and each() function

Post 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
uk1simon
Forum Newbie
Posts: 2
Joined: Sun Sep 19, 2010 11:16 am

Re: foreach loop and each() function

Post by uk1simon »

Alright I've found a solution.
I need to use reset() function.


Thanks,
Simon
Post Reply