← Back to PHP Course | Chapter 7: Arrays | Lesson 9 of 13

PHP Multidimensional Arrays

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
<?php
$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob", "age" => 25],
];
print_r($users);
?>

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
<?php
$matrix = [[1, 2], [3, 4]];
echo $matrix[1][0] . "\n";

$users = [["email" => "[email protected]"]];
echo $users[0]['email'];
?>

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
<?php
$rows = [
    ["id" => 1, "name" => "Alice"],
    ["id" => 2, "name" => "Bob"],
];
$rows[0]["name"] = "Alicia";
print_r($rows);
?>

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
<?php
$grid = [[1, 2], [3, 4]];
foreach ($grid as $row) {
    foreach ($row as $cell) {
        echo $cell . " ";
    }
    echo "\n";
}
?>

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
<?php
$data = ["user" => ["name" => "Alice", "roles" => ["admin", "editor"]]];
print_r($data);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.