PHP Multidimensional Arrays

A multidimensional array is an array whose elements are themselves arrays, letting you model tables and other nested data.

Arrays inside arrays

So far each array element has held a single value. A multidimensional array holds arrays as its values, so you can represent structures that have more than one dimension, such as rows and columns in a spreadsheet or a list of records where each record has several fields. The number of dimensions is simply how many index steps you take to reach a scalar value.

A two-dimensional array

<?php
$grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

echo $grid[0][0];   // 1  (row 0, column 0)
echo $grid[1][2];   // 6  (row 1, column 2)
echo $grid[2][1];   // 8  (row 2, column 1)
?>

The first index selects the outer element, and the second index reaches into the array stored there. You can keep nesting deeper, though arrays more than two or three levels deep are often a sign that a dedicated class would model the data more clearly.

Combining associative and nested arrays

The most useful multidimensional arrays in real applications mix numeric outer keys with associative inner arrays. This pattern mirrors a database result set: a numbered list of rows, where each row is a labelled record.

A list of records

<?php
$employees = [
    ["name" => "Ravi",  "role" => "Engineer", "salary" => 90000],
    ["name" => "Mei",   "role" => "Designer", "salary" => 85000],
    ["name" => "Omar",  "role" => "Manager",  "salary" => 95000],
];

echo $employees[1]["name"];   // Mei
echo $employees[2]["role"];   // Manager
?>

Looping over nested data

To walk through a multidimensional array you nest one loop inside another, or use a single foreach when the inner arrays are records you want to unpack by key.

Iterating a list of records

<?php
$employees = [
    ["name" => "Ravi", "salary" => 90000],
    ["name" => "Mei",  "salary" => 85000],
];

foreach ($employees as $person) {
    echo $person["name"] . " earns " . $person["salary"] . "\n";
}
?>
  • Reach a value by chaining index steps, one per dimension.
  • Use nested foreach loops to visit every cell of a grid.
  • Use a single foreach when each outer element is a self-contained record.
  • Keep nesting shallow; deeply nested arrays are hard to read and maintain.
Note: Accessing a missing inner key, such as $grid[5][0] when there is no row 5, triggers an undefined key warning and returns null. Validate indexes or use isset() before reaching into nested levels.
Note: print_r() and var_dump() indent nested arrays, which makes them the fastest way to understand the shape of an unfamiliar multidimensional array.