Page 1 of 1

looping an associative array

Posted: Thu Mar 20, 2008 11:57 am
by mlecho
if i have an associative array like this:

Code: Select all

 
Array ( [facility_num] => asdfas [facility] => dsa [attention] => asdf [title] => asdf [address] => asdf [suite] => asfas [city] => asdfsasdafsw [state] => asdf [zip] => 2423 [contact_num] => 33df [dvd_qty] => 35d [vhs_qty] => a ) 
 
how can i loop through it? i tried something like this:

Code: Select all

 
for($i=0;$i<count($rf);$i++)
    {
        echo ($rf[$i]."<br>");
    }
 
and

Code: Select all

 
$i=0;
    while($i<=count($rf))
    {
        echo ($rf[$i]."<br>");
        $i++;
    }
 
which are the same thing, but how can i loop through that?

Re: looping an associative array

Posted: Thu Mar 20, 2008 12:43 pm
by Zoxive

Code: Select all

foreach($rf as $key=>$value){
  // $key
  // $value
}

Code: Select all

while ($value = current($rf)) {
   //$key = key($rf)
   //$value
    next($rf);
}
2 Examples, there are more also.

Re: looping an associative array

Posted: Thu Mar 20, 2008 1:01 pm
by mattw
Foreach is probably a better choice:

Code: Select all

 
foreach ($rf as $val) {
  print $val . "<br />";
}
 
You can skip the $key portion if you're not using it.

You can also do:

Code: Select all

 
while (list($key,$val) = each($rf)) {
  print $val . "<br />";
}
 
list() can be useful for looping arrays of associative arrays in particular.

It's probably inefficient to call count() in a loop for performance reasons, and depending on what you're doing in the loop, could produce unexpected results.

Re: looping an associative array

Posted: Thu Mar 20, 2008 2:45 pm
by mlecho
thanks...i know that was basic....