Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Associative Arrays

An associative array is what nerds and gurus like to refer to as a "hash".

In a hotel there are rooms that are numbered (this is the analogy I used to discuss List arrays), and there are also rooms that have names and not numbers eg 'the honeymoon suite', 'the presidential suite', 'the kitchen'...

An associative array can be considered to be like a 'hotel' whose rooms are 'named' and not numbered. In programming a room's 'name' is called a key and the 'occupants' (or 'contents') of the room are called a value.

Creating an Associative Array

The syntax for creating an associative array is:

$arrayName = array("NameofRoom1" => "valueOfRoom1",
                   "NameofRoom2" => "valueOfRoom2",
                   "NameofRoom3" => "valueOfRoom3"   );

If put in a more professional manner the syntax will be:

$arrayName = array("key 1" => "value 1",
                   "key 2" => "value 2",
                   "key 3" => "value 3"   );

A perfect example of how an associative array can be used is to hold an employee record:

$employee = array("Name" => "Skinny Jimmy",
                  "Phone" => "037 771064",
                  "Age" =>  "27");

This effectively creates an array that would look something like this:

NamePhoneAge
Skinny Jimmy037 77106427

To reference (or extract) any of the $employee fields you use the key to reference the value. For example:

print $employee["Name"];
print "<br>". $employee["Age"]);

This will produce:

Skinny Jimmy
27

Remember the <br> in the second line of the above code snippet is a HTML line break tag that causes 27 to appear on the next line.

We have been printing "some" of an array's contents. Wouldn't it be nice to able to print all the contents of an array in one go?!

<< Adding Items to an Array | Traversing an Array >>

JamHitz Productions