header
 
     
 
pixel
pixel pixel

Looping through an associative array

Associative array doesn't use sequential numbers as its index like regular arrays which means you can't use a standard for next loop. For example, a regular array with sequential numbers for its indices takes the form:
$arrayname[0]='something';
$arrayname[1]=somethingelse';

An associative array (or 'hash table', thanx Echo) might take the form:
$arrayname['author'] = "John Cook";
$arrayname['country'] = "Australia";

A more universal method of looping through both types of arrays than the usual for($i=0; $i<count(array); $i++) is the following code:
<?php
foreach($arrayname as $key=>$value)
    {
    echo 
$key.": ".$value;
    }
?>

Unhelpful Helpful Rating 4.0 (score out of 5, no. of ratings: 16)
Comments
Comment by Echo on 2004-04-22
The proper name for this kind of 'unconventional array' is "hash table".

Comment by John Cook on 2004-04-27
Thanx for the comment, it inspired me to get a little more precise with my terminology. The proper terminology is 'associative array' so I've edited the wording (with a reference to 'hash tables' which admittedly I'd not heard of).

Comment by Channa on 2005-12-02
Good one!

Comment by martin on 2007-06-04
How can i go about printing out only 4 array elements per row? Supposing that $arrayname is being retrived from a database.

Post a Comment
Name
Email
(optional)
Comment
RatingUnhelpful Helpful
Security Image* (this is just to prevent spam submissions)
Security Image