Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Multidimensional Arrays

PHP – Multidimensional Arrays

A multidimensional array is an array that contains one or more arrays.

PHP supports multidimensional arrays that can be two, three, four, five, or more levels deep, although arrays deeper than three levels can be challenging to manage for most users.

The dimension of an array indicates how many indices are required 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.

PHP – Two-dimensional Arrays

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

First, let’s examine the following table:

Name

Stock

Sold

Volvo

22

18

BMW

15

13

Saab

5

2

Land Rover

17

15

We can store the data from the table above in a two-dimensional array as follows:

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

The two-dimensional $cars array now contains four arrays and has two indices: row and column.

To access the elements of the $cars array, we need to specify both indices (row and column):

Example

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

We can also use a for loop inside another for loop to access the elements of the $cars array (while still specifying both indices):

Example

 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>";
}