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 />'; } ?> Quote Link to comment 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 Quote Link to comment 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. Quote Link to comment 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 />'; } ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.