A multidimensional array is the same as in any other programming language: an array containing one or multiple other arrays. Multidimensional arrays are a very useful concept while.
Althouth you will normally find and use two or three levels of multidimensional arrays, you can have as many levels as you like or your memory usage allows you.
A multi-dimensional array is an array of arrays and any contained array can contain a key/value pairs, or another array.
Here is a real-world example of data that can be stored inside a multidimensional array.
Name | Birth day | Birth month | Birth year |
---|---|---|---|
Josh | 12 | 5 | 1984 |
Mary | 17 | 12 | 1981 |
Rose | 28 | 1 | 1992 |
Now let's store this table into a multi-dimensional array
php<?php
$family = array (
array("Josh",12, 5,1984),
array("Mary",17,12,1981),
array("Rose",28, 1,1992)
);
?>
Remember from our previous array tutorial that the above array is the same as below because the array keys are assumed as follows:
php<?php
$family = array (
0 => array( 0 => "Josh", 1 => 12, 2 => 5, 3 => 1984),
1 => array( 0 => "Mary", 1 => 17, 2 => 12, 3 => 1981),
2 => array( 0 => "Rose", 1 => 28, 2 => 1, 3 => 1992)
);
?>
Please note that this is an example of a two-dimension array. If you want to print names and years of birth for these three family members you should access the values like this:
php<?php
echo $family[0][0]." born in ". $family[0][3]."<br />";
echo $family[1][0]." born in ". $family[1][3]."<br />";
echo $family[2][0]." born in ". $family[2][3]."<br />";
?>
Let's take this example further and complicate it just a little bit while building a three-dimensional array from the same data.
php<?php
$family = array (
array("Josh",array(12, 5,1984) ),
array("Mary",array(17,12,1981) ),
array("Rose",array(28, 1,1992) )
);
?>
To print out Mary data, for example, you will do it like this:
php<?php
echo $family[1][0]." born in ". $family[1][1][2]."<br />";
?>
Great! Using numbers as keys keeps everything simple but sometimes it is harder to see what kind of data contains every variable. Here is how we can resolve this issue
php<?php
$family = array (
array('name' => "Josh", 'birthday' => array('day' => 12, 'month' => 5, 'year' => 1984) ),
array('name' => "Mary", 'birthday' => array('day' => 17, 'month' =>12, 'year' => 1981) ),
array('name' => "Rose", 'birthday' => array('day' => 28, 'month' => 1, 'year' => 1992) )
);
?>
This could look like a more complicated array, but the date is actually explaining itself. Here is why we say this:
php<?php
// loop throw all family members and print their names and year they born in
foreach ($family as $member) {
echo $member['name']." born in ". $member['birthday']['year']."<br />";
}
?>
You can also place a
foreach
inside
foreach
statement to loop o deaper level of an array, but beyont the subject of this tutorial.