PHP Multidimensional Arrays
In this page:
Introduction to Multidimensional Arrays
A multidimensional array is simply an array whose values are themselves arrays, letting you model grid-like or nested data such as a spreadsheet of rows and columns, or a list of users each with their own set of properties.
Example: Introduction to Multidimensional Arrays
<?php
$users = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
];
print_r($users);
?>
Login to try C/C++/Java/PHP code in the editor
Accessing Nested Elements
You access a nested value by chaining index brackets, like $matrix[1][2] for a 2D grid or $users[0][email] for the email of the first user in a list of associative arrays.
Example: Accessing Nested Elements
<?php
$matrix = [[1, 2], [3, 4]];
echo $matrix[1][0] . "\n";
$users = [["email" => "[email protected]"]];
echo $users[0]['email'];
?>
Login to try C/C++/Java/PHP code in the editor
Modifying Multidimensional Arrays
A common real-world shape is an array of associative arrays — for example, database query results are typically returned this way, with each outer element representing one row and its inner keys representing columns.
Example: Modifying Multidimensional Arrays
<?php
$rows = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"],
];
$rows[0]["name"] = "Alicia";
print_r($rows);
?>
Login to try C/C++/Java/PHP code in the editor
Looping Through Multidimensional Arrays
Nested foreach loops are the standard way to walk a multidimensional array: an outer loop for each row and an inner loop for each column, which is exactly how you'd render an HTML table from tabular data.
Example: Looping Through Multidimensional Arrays
<?php
$grid = [[1, 2], [3, 4]];
foreach ($grid as $row) {
foreach ($row as $cell) {
echo $cell . " ";
}
echo "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Multi-level Arrays
print_r() or var_dump() are invaluable for debugging multidimensional arrays, since they reveal the full nested structure and types at a glance instead of you having to guess how deep the nesting goes.
Example: Multi-level Arrays
<?php
$data = ["user" => ["name" => "Alice", "roles" => ["admin", "editor"]]];
print_r($data);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: