[ Team LiB ] Previous Section Next Section

Multidimensional Arrays

Until now, we've simply said that elements of arrays are values. In our $character array, three of the elements held strings and one held an integer. The reality is a little more complex, however. In fact, an element of an array could be a value, an object, or even another array. A multidimensional array is an array of arrays. Imagine an array that stores an array in each of its elements. To access the third element of the second element, we would have to use two indices:


$array[1][2]

The fact that an array element can itself be an array enables you to create sophisticated data structures relatively easily. Listing 7.1 defines an array that has an associative array as each of its elements.

Listing 7.1 Defining a Multidimensional Array
 1:<!DOCTYPE html PUBLIC
 2:  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 7.1 Defining a Multidimensional Array</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11:
12: $characters = array (
13:       array (
14:         "name"=> "bob",
15:         "occupation" => "superhero",
16:         "age" => 30,
17:         "specialty" =>"x-ray vision"
18:       ),
19:       array (
20:         "name" => "sally",
21:         "occupation" => "superhero",
22:         "age" => 24,
23:         "specialty" => "superhuman strength"
24:       ),
25:       array (
26:         "name" => "mary",
27:         "occupation" => "arch villain",
28:         "age" => 63,
29:         "specialty" =>"nanotechnology"
30:       )
31:     );
32:
33: print $characters[0][occupation];
34: // prints "superhero"
35: ?>
36: </div>
37: </body>
38: </html>

Notice that we have nested array construct calls within an array construct call. At the first level, we define an array. For each of its elements, we define an associative array.

Accessing $characters[2], therefore, gives us access to the third associative array (beginning on line 25) in the top-level array (beginning on line 12). We can then access any of the associative array's fields. $characters[2]['name'] will be mary, and $characters[2]['age'] will be 63.

When this concept is clear, you will be able to easily create complex combinations of associative and numerically indexed arrays.

    [ Team LiB ] Previous Section Next Section