drtanz Posted May 1, 2008 Share Posted May 1, 2008 hi i am using the following code to loop through one array. I am wondering why the two loops won't work together, I must comment the first one for the second one to work :S why is this? <?php $prices = array('Tires'=>100,'Oil'=>10,'Spark Plugs'=>4); foreach ($prices as $key => $price) { echo $key .'=>'.$price.'<br />'; } while ($element = each($prices)) { echo $element['key']; echo ' - '; echo $element['value']; echo '<br />'; } ?> Link to comment https://forums.phpfreaks.com/topic/103689-help-in-looping-through-associative-arrays/ Share on other sites More sharing options...
drtanz Posted May 1, 2008 Author Share Posted May 1, 2008 the output im getting is: Tires=>100 Oil=>10 Spark Plugs=>4 i tried it on another server and i get the same results, it should also be displaying the output of the second while loop :S Link to comment https://forums.phpfreaks.com/topic/103689-help-in-looping-through-associative-arrays/#findComment-530893 Share on other sites More sharing options...
Aeglos Posted May 1, 2008 Share Posted May 1, 2008 That's because both constructs (foreach() and each() ) use the internal array's pointer (each array has it's own) that indicates which element are they looking at currently, but when they finish iterating through the whole array the pointer is left at the end and not at the beginning again. So after the foreach() the array's pointer is at the end of the array, and when you call the next each() function it tries to traverse the array starting from the pointer, that is, the end, thus it immediatly exits. Use the reset() function to return the pointer to the first element, like this: $prices = array('Tires'=>100,'Oil'=>10,'Spark Plugs'=>4); foreach ($prices as $key => $price) { echo $key .'=>'.$price.'<br />'; } reset($prices); //Resets the pointer. while ($element = each($prices)) { echo $element['key']; echo ' - '; echo $element['value']; echo '<br />'; } That should work. Link to comment https://forums.phpfreaks.com/topic/103689-help-in-looping-through-associative-arrays/#findComment-530894 Share on other sites More sharing options...
drtanz Posted May 1, 2008 Author Share Posted May 1, 2008 yes thanks that's it, my updated code including the list construct as well: <?php $prices = array('Tires'=>100,'Oil'=>10,'Spark Plugs'=>4); foreach ($prices as $key => $price) { echo $key .'=>'.$price.'<br />'; } echo '<br />'; reset($prices); while ($element = each($prices)) { echo $element['key']; echo ' -- '; echo $element['value']; echo '<br />'; } echo '<br />'; reset($prices); while (list($product,$price) = each($prices)){ echo $product.' - '; echo $price.'<br />'; } ?> Link to comment https://forums.phpfreaks.com/topic/103689-help-in-looping-through-associative-arrays/#findComment-530897 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.