PHP Multidimensional Arrays

In the previous chapters of this tutorial, we have already learned that an array is a simple list of key/value pairs.

However, sometimes you may want to store values with more than one key.

You can store data using multidimensional arrays.

PHP - Multidimensional Array

A multidimensional array refers to an array that contains one or more arrays.

PHP can understand two, three, four, or five-level arrays, or even more levels. However, arrays deeper than three levels are difficult for most people to manage.

Note:The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array, you need two indices to select an element
  • For a three-dimensional array, you need three indices to select an element

PHP - Two-dimensional Array

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, let's take a look at the following table:

Brand Inventory Sales
Volvo 33 20
BMW 17 15
Saab 5 2
Land Rover 15 11

We can store the data from the above table in a two-dimensional array like this:

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

Now this two-dimensional array contains four arrays and it has two indices (subscripts): row and column.

To access elements of the $cars array, we must use two indices (row and column):

Example

<?php
echo $cars[0][0].": Inventory: ".$cars[0][1].", Sales: ".$cars[0][2].".<br>";
echo $cars[1][0].": Inventory: ".$cars[1][1].", Sales: ".$cars[1][2].".<br>";
echo $cars[2][0].": Inventory: ".$cars[2][1].", Sales: ".$cars[2][2].".<br>";
echo $cars[3][0].": Inventory: ".$cars[3][1].", Sales: ".$cars[3][2].".<br>";
?>

Run Example

We can also use another for loop inside the for loop to get elements from the $cars array (we still need to use two indices):

Example

<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}
?>

Run Example