Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.
In this tutorial you learn how to create multidimensional arrays, how to access elements in a multidimensional array, and how to loop through multidimensional arrays.
How to create a multidimensional array
You create a multidimensional array using the array()
construct, much like creating a regular array. The difference is that each element in the array you create is itself an array.
For example:
$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);
The above example creates a 2-dimensional array. The top-level array contains 3 elements. Each element is itself an array containing 3 values.
You can also use associative arrays in multidimensional arrays. The following example creates an indexed array containing 3 associative arrays:
$movies = array(
array(
"title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954
),
array(
"title" => "Full Metal Jacket",
"director" => "Stanley Kubrick",
"year" => 1987
),
array(
"title" => "Mean Streets",
"director" => "Martin Scorsese",
"year" => 1973
)
);
You can nest arrays as many levels deep as you like (although it’s rare to go higher than 3 levels). Here’s a 3-dimensional array:
$myArray = array(
array(
array( value1, value2 ),
array( value3, value4 )
),
array(
array( value5, value6 ),
array( value7, value8 )
)
);
Accessing elements in a multidimensional array
To access multidimensional array elements, you can use the same square bracket syntax that you use with regular arrays. If you want to access the second-level array elements in a 2-dimensional array, just use 2 sets of square brackets — for example:
$myArray = array(
array( "one", "two", "three" ),
array( "four", "five", "six" )
);
// Displays "six"
echo $myArray[1][2];
?>
Here are some examples that access various elements in the $movies
multidimensional array created earlier:
echo "The title of the first movie:<br />";
echo $movies[0]["title"] . "<br /><br />";
echo "The director of the third movie:<br />";
echo $movies[2]["director"] . "<br /><br />";
echo "The nested array contained in the first element:<br />";
print_r( $movies[0] );
echo "<br /><br />";
The above code produces the following output:
The title of the first movie: Rear Window The director of the third movie: Martin Scorsese The nested array contained in the first element: Array ( [title] => Rear Window [director] => Alfred Hitchcock [year] => 1954 )
The last example uses $movies[0]
to access the entire nested array contained in the first element of the top-level array, then uses print_r()
to display the array’s contents. (Find out more about print_r()
in Working With Array Elements in PHP.)
Looping through multidimensional arrays
Just as with regular, single-dimensional arrays, you can use foreach
to loop through multidimensional arrays. To do this, you need to create nested foreach
loops — that is, one loop inside another:
- The outer loop reads each element in the top-level array.
- For each of those top-level elements, the inner loop moves through the array contained in the top-level element, and so on.
Here’s an example that creates a 2-dimensional array of movie information, then loops through the array, displaying the information in the page:
$movies = array(
array(
"title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954
),
array(
"title" => "Full Metal Jacket",
"director" => "Stanley Kubrick",
"year" => 1987
),
array(
"title" => "Mean Streets",
"director" => "Martin Scorsese",
"year" => 1973
)
);
foreach ( $movies as $movie ) {
echo '<dl style="margin-bottom: 1em;">';
foreach ( $movie as $key => $value ) {
echo "<dt>$key</dt><dd>$value</dd>";
}
echo '</dl>';
}
The above script displays the following:
title Rear Window director Alfred Hitchcock year 1954 title Full Metal Jacket director Stanley Kubrick year 1987 title Mean Streets director Martin Scorsese year 1973
Summary
In this tutorial you’ve seen how to create, manipulate, and loop through multidimensional arrays in PHP. Multidimensional arrays are useful for all sorts of things, such as holding multiple database records and storing data to display in tables. Now that you know how to use them, you can add a new level of sophistication to your PHP scripts.
Happy coding!
Christian Scholz-Flöter says
Thanks for this comprehensive write-up. I tend to forget how arrays are created in PHP. Now, I have this neat article to look it up. 🙂
Matt Doyle says
Thanks Christian! Glad you found the article helpful 🙂
toni says
Thanks broo
Help me to figure “names” as an array index 😀
toni says
echo $entries[0][cn][0].””;
echo $entries[0][description][0].””;
ldap_get_entries
toni says
echo $entries[0][cn][0];
echo $entries[0][description][0];
ldap_get_entries
Thomas Bishop says
Really good, no-nonsense account. Thank you.
Matt Doyle says
You’re welcome, Thomas. I’m glad it helped 🙂
gerald says
hello am i right with this code, because they are not function
Matt Doyle says
What’s the error message?
Also, never ever insert values from
$_POST
straight into an SQL string – it’s a massive security hole. Use a prepared statement with placeholders instead.Kevin says
Hey Matt ~
Just a thank you for this post. I get a lot of help and guidance from the enormous numbers of posts on StackOverflow, but every now and again I come across a really nicely explained tutorial or guide like this one. I’m building my first true application in PHP (in conjunction with delivering it through WordPress) and having to relearn a lot of stuff.
At any rate, much appreciated. Hope you’re fairing well under the novel circumstances.
~K
Matt Doyle says
You’re welcome, Kevin! I’m glad my tutorial helped. 🙂 All good here – hope you are doing well also.
Simon says
Hi Matt,
Thanks for the write-up. I do get the feel for the array stuff, but in my case I do not know the size (x and y) of the array I need. I have some 20 or 30 lamps that may be switched on or off. As it happens I get a timestamp, the lamp involved and the new state (on or off). So it seems logical to have an object “switchstamp” that I can array_push onto the array of the lamp switching. That way I get arrays of timestamps per lamp. And as many as I have lamps arrays of that. This is going to be used for making a graph showing when what lamp is switched on a 24hr timescale. So arrays of arrays, but I don’t know how many lamps and how often are switched.
How to declare such an array?
Mohammad Arif Rahim says
Hi,
Can you also describe, how to collected and insert into an previously created array in a function from OOP perspective.
SADIK KABIR AHMAD says
idon’t why it show me error please can you help me
$data = Array(
do{
$loadresult[‘subject_code’]=>[‘color’=>[255, 0, 100],’value’=> $loadresult [‘test’]]
}while($loadresult = $loadquery->fetch(PDO::FETCH_ASSOC));
);
Andrew Koll. says
Dear Matt,
Your teaching is amazingly short, clear and awesome. I understand lots of things for the first time in my php life. You clearly points to the possible failures. Thank you so much! I will be much more brave with arrays from now. Thank you!
Matt Doyle says
You’re welcome, Andrew. Thanks for your comment 🙂