[ Team LiB ] Previous Section Next Section

Associative Arrays

Numerically indexed arrays are useful for storing values in the order they were added or according to a sort pattern. Sometimes, though, you need to access elements in an array by name. An associative array is indexed with strings between the square brackets rather than numbers. Imagine an address book. Which would be easier, indexing the name field as 4 or as name?

Again, you can define an associative array using either array() or the array operator [].


The division between an associative array and a numerically indexed array is not absolute in PHP. They are not separate types as arrays and hashes are in Perl are. Nevertheless, you should treat them separately because each demands different strategies for access and manipulation.

Defining Associative Arrays with the array() Construct

To define an associative array with the array() construct, you must define both the key and value for each element. The following code creates an associative array called $character with four elements:

$character = array (
      "name" => "bob",
      "occupation" => "superhero",
      "age" => 30,
      "special power" => "x-ray vision"

We can now access any of the fields of $character:

print $character['age'];

The keys in an associative array are strings, but in its default error reporting state the engine won't complain if array keys aren't quoted.

Omitting quotation marks for array keys is poor practice, however. If you use unquoted strings as keys and your error reporting is set to a higher-than-standard level, the engine will complain every time such an element is met. Even worse, if an unquoted array key coincides with a constant, the value of the constant will be substituted for the key as typed.


You should enclose an associative array key with quotation marks when the key in question is a string literal:

print $character[age]; // wrong
print $character["age"]; // right

If the key is stored in a variable, you do not need to use quotation marks:

$agekey = "age";
print $character[$agekey]; // right

Directly Defining or Adding to an Associative Array

You can create or add a name/value pair to an associative array simply by assigning a value to a named element. In the following, we re-create our $character array by directly assigning a value to each key:

$character["name"] = "bob";
$character["occupation"] = "superhero";
$character["age"] = 30;
$character["special power"] = "x-ray vision";

    [ Team LiB ] Previous Section Next Section