In the previous tutorial, we have learn about Arrays in PHP, In that we defined an array as a variable that stores a group of values of a similar kind. While single arrays store only a single list of key/value pair, multidimensional arrays are store more datasets with different key/value pairs.

PHP Multidimensional Arrays :

Multidimensional arrays can be used in the case of the calculation of something whose parameters are tied together.

For instance, the amount of tax paid by each employee in a company. It may store the values for total income and percentage tax, for a two-dimensional array.

Multidimensional arrays may be of any size. However, a practical array may only have a maximum of 3 dimensions for the ease of management.

In order to select a member of multidimensional array, you will need its indices. 2-D arrays need 2 indices, 3-D needs 3 indices, and etc.

Multidimensional Arrays :

We look at the example in which we compare the performance of the teams in the English Premier League for 2 seasons.

Team2014/20152015/2016
Manchester United12
Chelsea31
Manchester City23
Arsenal45
Tottenham Hotspurs54

In order to display this information by the use of arrays, we can put it as in the example below:


$teams=array(array("Manchester United",1,2),array("Chelsea",3,1),array("Manchester City",2,3),array("Arsenal",4,5),array("Tottenham Hotspurs",5,4));

Our League standings comparison has been stored in the array called “$teams.” This array has five arrays within it and two rows and columns, which give us the indices.

In order extract a member one needs the following syntax:

$array_name[row][column]

Example :

<?php

$teams = array(array("Manchester United", 1, 2), array("Chelsea", 3, 1),
    array("Manchester City", 2, 3), array("Arsenal", 4, 5), array("Tottenham Hotspurs", 5, 4));
//this code would display results for the first team, which is the first row, with separate columns that represent team, first season, and second season. 
echo $teams[0][0] . " was position " . $teams[0][1] . " in 2014/2015 and " . $teams[0][2] . " in 2015/2016 in the EPL League</br>";
//this code would display results for the second team, which is the second row, with separate columns that represent team, first season, and second season. 
echo $teams[1][0] . " was position " . $teams[1][1] . " in 2014/2015 and " . $teams[1][2] . " in 2015/2016 in the EPL League</br>";
echo "<h2>Here are the results of the EPL League Comparison</h2>";
for ($row = 0; $row < 5; $row++) {
    for ($col = 0; $col < 3; $col++) {
        echo "</br>&emsp;" . $teams[$row][$col];
    }
}
?>

Output:

Manchester United was position 1 in 2014/2015 and 2 in 2015/2016 in the EPL League Chelsea was position 3 in 2014/2015 and 1 in 2015/2016 in the EPL League

Here are the results of the EPL League Comparison

Manchester United
1
2
Chelsea
3
1
Manchester City
2
3
Arsenal
4
5
Tottenham Hotspurs
5
4

Happy Learning 🙂