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 />';
}
?>	

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.

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 />';
}

?>	

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.