PHP Multidimensional Arrays

A simple design feature in PHP’s array syntax makes it possible to create arrays of more than one dimension. In fact, they can be as many dimensions as you like (although it’s a rare application that goes further than three). That feature makes it possible to include an entire array as a part of another one, and to be able to keep doing so, just like the old rhyme: “Big fleas have little fleas upon their backs to bite ’em. Little fleas have lesser fleas, add flea, ad infinitum.”

Let’s look at how this works by taking the associative array in the previous example and extending it;  see Example 6-10.

Example 6-10. Creating a multidimensional associative array

 $products = array(
 'paper' => array(
                  'copier' => "Copier & Multipurpose",
                   'inkjet' => "Inkjet Printer",
                   'laser' => "Laser Printer",
                    'photo' => "Photographic Paper"),
 'pens' => array(
                  'ball' => "Ball Point",
                  'hilite' => "Highlighters",
                   'marker' => "Markers"),
 'misc' => array(
                 'tape' => "Sticky Tape",
                 'glue' => "Adhesives",
                 'clips' => "Paperclips" )
 echo "<pre>";

 foreach($products as $section => $items)
     foreach($items as $key => $value)
          echo "$section:\t$key\t($value)<br>"; 
          echo ""; 

To make things clearer now that the code is starting to grow, I’ve renamed some of the elements. For example, because the previous array $paper is now just a subsection of a larger array, the main array is now called $products. Within this array, there are three items—paper, pens, and misc—each of which contains another array of key/value
pairs. If necessary, these subarrays could have contained even further arrays. For example, under a ball, there might be many different types and colours of ballpoint pens available in the online store. But for now, I’ve restricted the code to a depth of just two. Once the array data has been assigned, I use a pair of nested foreach … as loops to
print out the various values. The outer loop extracts the main sections from the top level of the array, and the inner loop extracts the key/value pairs for the categories within each section.
As long as you remember that each level of the array works the same way (it’s a key/ value pair), you can easily write code to access any element at any level. The echo statement makes use of the PHP escape character \t, which outputs a tab. Although tabs are not normally significant to the web browser, I let them be used for layout by using the <pre>…</pre> tags, which tell the web browser to format the text as preformatted and monospaced, and not to ignore whitespace characters such as tabs and line feeds. The output from this code looks like the following:

paper: copier (Copier & Multipurpose)
paper: inkjet (Inkjet Printer)
paper: laser (Laser Printer)
paper: photo (Photographic Paper)
pens: ball (Ball Point)
pens: hilite (Highlighters)
pens: marker (Markers)
misc: tape (Sticky Tape)
misc: glue (Adhesives)
misc: clips (Paperclips)


You can directly access a particular element of the array using square brackets, like this:

echo $products[‘misc’][‘glue’];

which outputs the value of Adhesives. You can also create numeric multi-dimensional arrays that are accessed directly by indexes rather than by alphanumeric identifiers. Example 6-11 creates the board for a chess game with the pieces in their starting positions.

Example 6-11. Creating a multidimensional numeric array

     $chessboard = array(
                 array('r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'),
                array('p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'),
                array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
                array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
               array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
               array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
               array('P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'),
               array('R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R')

echo "<pre>";

 foreach($chessboard as $row)

     foreach ($row as $piece)
             echo "$piece ";
            echo "<br>";

echo " </pre> "; 


In this example, the lowercase letters represent black pieces and the uppercase white. The key is r = rook, n = knight, b = bishop, k = king, q = queen, and p = pawn. Again, a pair of nested foreach … as loops walk through the array and displays its contents. The outer loop processes each row into the variable $row, which itself is an array because the $chessboard array uses a subarray for each row. This loop has two statements within it, so curly braces enclose them.
The inner loop then processes each square in a row, outputting the character ($piece) stored in it, followed by a space (to square up the printout). This loop has a single statement, so curly braces are not required to enclose it. The and tags ensure that the output displays correctly, like this:

r n b q k b n r
p p p p p p p p


You can also directly access any element within this array using square brackets, like

echo $chessboard[7][3];

This statement outputs the uppercase letter Q, the eighth element down and the fourth
along (remembering that array indexes start at 0, not 1).