[Previous] [Contents] [Next]

Associative arrays

An associative array uses string indexes-or keys-to access values stored in the array. An associative array can be constructed using array( ), as shown in the following example, which constructs an array of integers:

$array = array("first"=>1, "second"=>2, "third"=>3);
// Echo out the second element: prints "2"
echo $array["second"];

The same array of integers can also be created with the bracket syntax:

$array["first"] = 1;
$array["second"] = 2;
$array["third"] = 3;

There is little difference between using numerical or string indexes to access values. Both can reference elements of an associative array, but this is confusing and should be avoided in practice.

Associatively indexed arrays are particularly useful for interacting with the database tier. Arrays are used extensively in Chapter 4, Chapter 5, and Chapter 6, and more examples and array-specific functions are presented there.

Heterogeneous arrays

The values that can be stored in a single PHP array don't have to be of the same type; PHP arrays can contain heterogeneous values. The following example shows the heterogeneous array $mixedBag:

$mixedBag = array("cat", 42, 8.5, false);

The function var_dump( ) displays the contents (with a little whitespace added for clarity):

array(4) { [0]=> string(3) "cat"
           [1]=> int(42)
           [2]=> float(8.5)
           [3]=> bool(false) }

[Previous] [Contents] [Next]