Jump to content

help in looping through associative arrays


drtanz

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.