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.
Type Of Multidimensional Array
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):
<?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>";
?>
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):
<?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>";
}
?>
Food Stock 0
Pizza
99
59
Food Stock 1
Cakes
29
32
Food Stock 2
Tea
25
2
Food Stock 3
Coffee
65
15
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning