PHP - Multidimensional Arrays
When the items of an array are themselves arrays, whether one or several, you have a multidimensional array.
PHP lets you nest them two, three, four, five levels deep or further. In practice, though, most people find anything beyond three levels hard to manage.
PHP - Two-dimensional Arrays
A two-dimensional array is simply an array whose items are arrays. Add another layer, so that the inner arrays hold arrays of their own, and you get a three-dimensional array.
This shape suits data that comes in rows and columns. Here is what it looks like:
Access two-dimensional array elements
Reading a value from $cars takes two indices, the first for the row and the second for the column:
Output: PHP script
<?php
$cars = array (
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
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>";
?>
Two-dimensional array definition
Each inner array is one row of a table, with the brand, the number in stock and the number sold:
<?php
$cars = array (
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
?>
PHP - Looping Through Multidimensional Arrays
Going through a multidimensional array takes a for or a foreach loop.
The number of dimensions tells you how many indices it takes to reach a single element:
- Two dimensions mean two indices
- Three dimensions mean three indices
Loop with nested for loops
One for loop nested in another visits every element of $cars. The outer one moves through the rows, the inner one through the columns, and each element is still reached with both indices:
Output: PHP script
<?php
$cars = array (
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
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>";
}
?>
Loop with nested foreach loops
Nested foreach loops can do the same job without any index numbers. This time the values are printed as an HTML table:
Output: PHP script
<?php
$cars = array (
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
echo "<table>";
echo "<tr><th>Brand</th><th>Stock</th><th>Sold</th></tr>";
foreach ($cars as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>" . $cell . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>