In associative array, we can store one value with only one key.
But if we want to store one or more keys for one value.
This can be done using multi-dimensional arrays.
A multi-dimensional array can be two-dimensional or three-dimensional array depending on indices.
A two-dimensional array is known as array of arrays.
A three-dimensional array is known as array of arrays of arrays.
Using multi-dimensional array you can store data in table form.
Let’s see following example:
Subject | Marks | Grade |
---|---|---|
Mathematics | 23 | D |
Science | 45 | C |
English | 65 | B |
Drawing | 80 | A |
Now this above table can be stored using multi-dimensional array as.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $Scorecard = array ( array("Mathematics", 23, "D"), array("Science", 45, "C"), array("English", 65, "B"), array("Drawing", 80, "A"), ); echo "Marks in subject ".$Scorecard[0][0]." is ".$Scorecard[0][1]." with grade ".$Scorecard[0][2]."<br>"; echo "Marks in subject ".$Scorecard[1][0]." is ".$Scorecard[1][1]." with grade ".$Scorecard[1][2]."<br>"; echo "Marks in subject ".$Scorecard[2][0]." is ".$Scorecard[2][1]." with grade ".$Scorecard[2][2]."<br>"; echo "Marks in subject ".$Scorecard[3][0]." is ".$Scorecard[3][1]." with grade ".$Scorecard[3][2]."<br>"; ?> |
Output:
1 2 3 4 |
Marks in subject Mathematics is 23 with grade D Marks in subject Science is 45 with grade C Marks in subject English is 65 with grade B Marks in subject Drawing is 80 with grade A |
You can print this table using for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $Scorecard = array ( array("Mathematics", 23, "D"), array("Science", 45, "C"), array("English", 65, "B"), array("Drawing", 80, "A"), ); for ($row = 0; $row < 4; $row++) { for ($col = 0; $col < 4; $col++) { echo $Scorecard[$row][$col]." "; } echo "<br>"; } ?> |
Output:
1 2 3 4 |
Mathematics 23 D Science 45 C English 65 B Drawing 80 A |