Groups of Data: Using Multidimensional Arrays in PHP

As mentioned in “Array Basics” on page 57, the value of an array element can be another array. This is useful when you want to store data that has a more complicated structure than just a key and a single value. A standard key/value pair is fine for matching up a meal name (such as breakfast or lunch) with a single dish (such as Walnut Bun or Chicken with Cashew Nuts), but what about when each meal con­sists of more than one dish? Then, element values should be arrays, not strings.

Use the array() construct or the [] short array syntax to create arrays that have more arrays as element values, as shown in Example 4-28.

Example 4-28. Creating multidimensional arrays with array() and []

$meals = array(‘breakfast’ => [‘Walnut Bun’,’Coffee’],

 ‘lunch’ => [‘Cashew Nuts’, ‘White Mushrooms’],

 ‘snack’ => [‘Dried Mulberries’,’Salted Sesame Crab’]);

$lunches = [ [‘Chicken’,’Eggplant’,’Rice’],

    [‘Beef’,’Scallions’,’Noodles’],

    [‘Eggplant’,’Tofu’] ];

$flavors = array(‘Japanese’ => array(‘hot’ => ‘wasabi’,

‘salty’ => ‘soy sauce’),

‘Chinese’ => array(‘hot’ => ‘mustard’,

‘pepper-salty’ => ‘prickly ash’));

Access elements in these arrays of arrays by using more sets of square brackets to identify elements. Each set of square brackets goes one level into the entire array. Example 4-29 demonstrates how to access elements of the arrays defined in Example 4-28.

Example 4-29. Accessing multidimensional array elements

print $meals[‘lunch’][1];              // White Mushrooms 

print $meals[‘snack’][0];              // Dried Mulberries 

print $lunches[0][0];                  // Chicken 

print $lunches[2][1];                  // Tofu 

print $flavors[‘Japanese’][‘salty’]    // soy sauce 

print $flavors[‘Chinese’][‘hot’ ];     // mustard 

Each level of an array is called a dimension. Before this section, all the arrays in this chapter have been one-dimensional arrays. They each have one level of keys. Arrays such as $meals, $lunches, and $flavors, shown in Example 4-29, are called multidi­mensional arrays because they each have more than one dimension.

You can also create or modify multidimensional arrays with the square bracket syn­tax. Example 4-30 shows some multidimensional array manipulation.

Example 4-30. Manipulating multidimensional arrays

$prices[‘dinner’][‘Sweet Corn and Asparagus’] = 12.50;

$prices[‘lunch’][‘Cashew Nuts and White Mushrooms’] = 4.95;

$prices[‘dinner’][‘Braised Bamboo Fungus’] = 8.95;

$prices[‘dinner’][‘total’] = $prices[‘dinner’][‘Sweet Corn and Asparagus’] +

 $prices[‘dinner’][‘Braised Bamboo Fungus’];

$specials[0][0] = ‘Chestnut Bun’;

$specials[0][1] = ‘Walnut Bun’;

$specials[0][2] = ‘Peanut Bun’;

$specials[1][0] = ‘Chestnut Salad’;

$specials[1][1] = ‘Walnut Salad’;

// Leaving out the index adds it to the end of the array

// This creates $specials[1][2]

$specials[1][] = ‘Peanut Salad’;

To iterate through each dimension of a multidimensional array, use nested foreach() or for() loops. Example 4-31 uses foreach() to iterate through a multidimensional associative array.

Example 4-31. Iterating through a multidimensional array with foreach()

$flavors = array(‘Japanese’ => array(‘hot’ => ‘wasabi’,

‘salty’ => ‘soy sauce’),

   ‘Chinese’ => array(‘hot’ => ‘mustard’,

    ‘pepper-salty’ => ‘prickly ash’));

// $culture is the key and $culture_flavors is the value (an array)

foreach ($flavors as $culture => $culture_flavors) {

// $flavor is the key and $example is the value

foreach ($culture_flavors as $flavor => $example) {

print “A $culture $flavor flavor is $example.\n”;

}

}

Example 4-31 prints:

A Japanese hot flavor is wasabi.

A Japanese salty flavor is soy sauce.

A Chinese hot flavor is mustard.

A Chinese pepper-salty flavor is prickly ash.

The first foreach() loop in Example 4-31 iterates through the first dimension of $flavors. The keys stored in $culture are the strings Japanese and Chinese, and the values stored in $culture_flavors are the arrays that are the element values of this dimension. The next foreach() iterates over those element value arrays, copying keys such as hot and salty into $flavor, and values such as wasabi and soy sauce into $example. The code block of the second foreach() uses variables from both foreach() statements to print out a complete message.

Just like nested foreach() loops iterate through a multidimensional associative array, nested for() loops iterate through a multidimensional numeric array, as shown in Example 4-32.

Example 4-32. Iterating through a multidimensional array with for()

$specials = array( array(‘Chestnut Bun’, ‘Walnut Bun’, ‘Peanut Bun’),

 array(‘Chestnut Salad’,’Walnut Salad’, ‘Peanut Salad’) );

// $num_specials is 2: the number of elements in the first dimension of $specials

for ($i = 0 , $num_specials = count($specials); $i < $num_specials; $i++) {

// $num_sub is 3: the number of elements in each subarray

for ($m = , $num_sub = count($specials[$i]); $m < $num_sub; $m++) {

print “Element [$i][$m] is ” . $specials[$i][$m] . “\n”;

}

}

Example 4-32 prints:

Element [0][0] is Chestnut Bun

Element [0][1] is Walnut Bun

Element [0][2] is Peanut Bun

Element [1][0] is Chestnut Salad

Element [1][1] is Walnut Salad

Element [1][2] is Peanut Salad

In Example 4-32, the outer for() loop iterates over the two elements of $specials. The inner for() loop iterates over each element of the subarrays that hold the differ­ent strings. In the print statement, $i is the index in the first dimension (the ele­ments of $specials), and $m is the index in the second dimension (the subarray).

To interpolate a value from a multidimensional array into a double-quoted string or here document, use the curly brace syntax from Example 4-20. Example 4-33 uses curly braces for interpolation to produce the same output as Example 4-32. In fact, the only different line in Example 4-33 is the print statement.

Example 4-33. Multidimensional array element value interpolation

$specials = array( array(‘Chestnut Bun’, ‘Walnut Bun’, ‘Peanut Bun’),

array(‘Chestnut Salad’,’Walnut Salad’, ‘Peanut Salad’) );

// $num_specials is 2: the number of elements in the first dimension of $specials

for ($i = ( , $num_specials = count($specials); $i < $num_specials; $i++) {

// $num_sub is 3: the number of elements in each subarray

for ($m = , $num_sub = count($specials[$i]); $m < $num_sub; $m++) {

print “Element [$i][$m] is {$specials[$i][$m]}\n”;

}

}

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *