A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays deeper than three levels are hard to manage for most people.
A two-dimensional array is like a table with rows and columns. Imagine we have the following data:
| Name | Stock | Sold |
|---|---|---|
| Volvo | 22 | 18 |
| BMW | 15 | 13 |
| Saab | 5 | 2 |
We can store this data in a 2D array like this:
<?php
$cars = [
["Volvo", 22, 18],
["BMW", 15, 13],
["Saab", 5, 2]
];
?>
To access an element, we must point to the two indices (row and column):
<?php
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>";
?>
To display the entire contents of a multidimensional array, we use a nested loop — a loop inside another loop.
<?php
for ($row = 0; $row < 3; $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>";
}
?>
[0][1]) to access inner data.