Multidimensional arrays

PHP arrays can also hold other arrays creating multidimensional arrays. Example 2-4 shows how multidimensional arrays can be constructed.

Example 2-4. Examples of multidimensional arrays in PHP
   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "" >
  <title>Multi-dimensional arrays</title>
<body bgcolor="#ffffff">
<h2>A two dimensional array</h2>
  // A two dimensional array using integer indexes
  $planets = array(array("Mercury", 0.39, 0.38),
                   array("Venus", 0.72, 0.95),
                   array("Earth", 1.0, 1.0),
                   array("Mars", 1.52, 0.53) );
  // prints "Earth"
  print $planets[2][0]
<h2>More sophisticated multi-dimensional array</h2>
  // More sophisticated multi-dimensional array
  $planets2 = array(
    "Mercury"=> array("dist"=>0.39, "dia"=>0.38),
    "Venus"  => array("dist"=>0.39, "dia"=>0.95),
    "Earth"  => array("dist"=>1.0,  "dia"=>1.0,
    "Mars"   => array("dist"=>0.39, "dia"=>0.53,
                  "moons"=>array("Phobos", "Deimos")),
  // prints "Moon"
  print $planets2["Earth"]["moons"][0];

The first array constructed in Example 2-4 is two-dimensional and is accessed using integer indexes. The array $planets contains four elements, each of which is an array that contains three values: the planet name, the distance from the Sun, and the planet diameter relative to the Earth.

The second array in Example 2-4 is a little more sophisticated: the array $planets2 uses associative keys to identify an array that holds information about a planet. Each planet has an array of values that are associatively indexed by the name of the property that is stored; the array is effectively acting like a property list. For those planets that have moons, an extra property is added that holds an array of the moon names.

As stated in the introduction to this section, PHP arrays are very flexible. Many data structures-such as property lists, stacks, queues, and trees-can be created using arrays. We limit our usage of arrays to simple structures.