Multidimensional Arrays
PHP Multidimensional array is also known as an array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of a matrix which is represented by row * column.
- 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.
- The dimension of an array indicates the number of indices you need to select an element.
Type Of Multidimensional Array
- Two-Dimensional Array: For a two-dimensional array you need two indices to select an element
- Three-Dimensional Array: 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).
First, take a look at the following table:
| Name | Stock | Sold |
|---|---|---|
| Cake | 29 | 32 |
| Pizza | 99 | 59 |
| Tea | 25 | 2 |
| Coffee | 65 | 15 |
We can store the data from the table above in a two-dimensional array, like this:
$foods = array
(
array("Pizza",99,59),
array("Cakes",29,32),
array("Tea",25,2),
array("Coffee",65,15)
);
Now the two-dimensional $foods array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $foods array we must point to the two indices (row and column):
Example
<?php
$foods = array
(
array("Pizza",99,59),
array("Cakes",29,32),
array("Tea",25,2),
array("Coffee",65,15)
);
echo $foods[0][0].": In stock: ".$foods[0][1].", sold: ".$foods[0][2].".<br>";
echo $foods[1][0].": In stock: ".$foods[1][1].", sold: ".$foods[1][2].".<br>";
echo $foods[2][0].": In stock: ".$foods[2][1].", sold: ".$foods[2][2].".<br>";
echo $foods[3][0].": In stock: ".$foods[3][1].", sold: ".$foods[3][2].".<br>";
?>
Output :
Pizza: In stock: 99, sold: 59.
Cakes: In stock: 29, sold: 32.
Tea: In stock: 25, sold: 2.
Coffee: In stock: 65, sold: 15.
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 1:filename1.php
<?php
$foods = array
(
array("Pizza",99,59),
array("Cakes",29,32),
array("Tea",25,2),
array("Coffee",65,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Food Stock $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$foods[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Output:
Food Stock 0
Pizza
99
59
Food Stock 1
Cakes
29
32
Food Stock 2
Tea
25
2
Food Stock 3
Coffee
65
15
