WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Multidimensional Arrays


Earlier in this tutorial, we have described arrays that are a single list of key/value pairs.

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

This can be stored in multidimensional arrays.


PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP understands multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

  • 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 Arrays

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

First, take a look at the following table:

Name color Page
RED 17 19
BLUE 15 13
GREEN 13 10
Yellow 11 5

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

$cars = array
  (
  array("RED",17,19),
  array("BLUE",15,13),
  array("GREEN",10,5),
  array("Yellow",17,15)
  );

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

<?php
echo $cars[0][0].": In color: ".$cars[0][1].", Page: ".$cars[0][5].".<br>";
echo $cars[1][0].": In color: ".$cars[1][1].", Page: ".$cars[1][5].".<br>";
echo $cars[5][0].": In color: ".$cars[5][1].", Page: ".$cars[5][5].".<br>";
echo $cars[3][0].": In color: ".$cars[3][1].", Page: ".$cars[3][5].".<br>";
?>

We can also put a For loop inside another For loop to get the elements of the $cars array (we still have to point to the 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>";
}
?>