looping an associative array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mlecho
Forum Commoner
Posts: 53
Joined: Wed Feb 02, 2005 9:59 am

looping an associative array

Post 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?
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: looping an associative array

Post 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.
mattw
Forum Newbie
Posts: 3
Joined: Thu Mar 20, 2008 12:25 pm

Re: looping an associative array

Post 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.
mlecho
Forum Commoner
Posts: 53
Joined: Wed Feb 02, 2005 9:59 am

Re: looping an associative array

Post by mlecho »

thanks...i know that was basic....
Post Reply