LearnContact
Lesson 2122 min read

Multidimensional Arrays

Learn how to work with arrays of arrays to represent structured, tabular data, and how to loop over them with nested foreach.

Introduction

A single array is great for a flat list of values or one record's worth of fields. But real data is often structured like a table — multiple rows, each with the same set of columns. Think of a spreadsheet of students, a list of products with prices, or search results with several fields each.

PHP handles this naturally with multidimensional arrays: arrays whose values are themselves arrays. This lesson covers how to build them, how to access and modify nested values, how to loop over them with nested foreach loops, and works through a complete example that prints a small student report.

What You Will Learn
  • What a multidimensional array is and when to use one.
  • How to access nested values like $data[0]['name'].
  • How to loop over a multidimensional array using nested foreach loops.
  • How to build and print a small report from structured, tabular data.
  • How to update a value inside a nested array.

What is a Multidimensional Array?

A multidimensional array is simply an array where each element is itself an array. This is exactly how you represent a list of records — each "row" is an associative array of fields, and the outer array holds all of the rows together.

multidimensional-basic.php
<?php
$students = [
    ["name" => "Rahul", "grade" => 78],
    ["name" => "Priya", "grade" => 92],
    ["name" => "Aman", "grade" => 65],
];

print_r($students);
?>
Output
Array
(
    [0] => Array
        (
            [name] => Rahul
            [grade] => 78
        )

    [1] => Array
        (
            [name] => Priya
            [grade] => 92
        )

    [2] => Array
        (
            [name] => Aman
            [grade] => 65
        )

)
Think in Tables

It helps to picture a multidimensional array like this as a spreadsheet: the outer array is the table, each inner array is a row, and each key inside a row ("name", "grade") is a column.

Accessing Nested Values

To reach a value inside a nested array, chain the keys together: first the outer array's index (which row), then the inner array's key (which field).

accessing-nested.php
<?php
$students = [
    ["name" => "Rahul", "grade" => 78],
    ["name" => "Priya", "grade" => 92],
    ["name" => "Aman", "grade" => 65],
];

echo $students[0]["name"] . "\n";
echo $students[1]["grade"] . "\n";
echo $students[2]["name"] . " scored " . $students[2]["grade"] . "\n";
?>
Output
Rahul
92
Aman scored 65

You can nest arrays as deeply as you need — an array of arrays of arrays — though in practice most real-world data rarely goes beyond two or three levels before it makes sense to reach for objects instead.

Looping With Nested foreach

To process every value in a multidimensional array, use an outer foreach to loop over the rows, and an inner foreach (or direct key access) to loop over each row's fields.

nested-foreach.php
<?php
$students = [
    ["name" => "Rahul", "grade" => 78],
    ["name" => "Priya", "grade" => 92],
];

foreach ($students as $student) {
    foreach ($student as $field => $value) {
        echo "$field: $value\n";
    }
    echo "---\n";
}
?>
Output
name: Rahul
grade: 78
---
name: Priya
grade: 92
---

Often you already know the field names in advance, in which case you do not need a fully generic inner loop — you can just reference the known keys directly, as shown in the next example.

Worked Example: Student Report

Let's put this together into a small, complete program: a list of student records, each with a name and a grade, looped over to print a formatted report with a pass/fail label for each student.

student-report.php
<?php
$students = [
    ["name" => "Rahul", "grade" => 78],
    ["name" => "Priya", "grade" => 92],
    ["name" => "Aman", "grade" => 39],
    ["name" => "Sneha", "grade" => 55],
];

echo "--- Student Report ---\n";

foreach ($students as $index => $student) {
    $rowNumber = $index + 1;
    $status = $student["grade"] >= 40 ? "Pass" : "Fail";

    echo "$rowNumber. " . $student["name"] . " - " . $student["grade"] . "/100 - $status\n";
}
?>
Output
--- Student Report ---
1. Rahul - 78/100 - Pass
2. Priya - 92/100 - Pass
3. Aman - 39/100 - Fail
4. Sneha - 55/100 - Pass
What This Demonstrates

This example combines several concepts at once: a multidimensional array of associative arrays, the foreach ($arr as $key => $value) syntax to get a row number, nested-value access with $student["grade"], and the ternary operator for a compact pass/fail check.

Modifying Nested Values

You can update a value deep inside a multidimensional array the same way you access it — by chaining the keys on the left side of an assignment.

modifying-nested.php
<?php
$students = [
    ["name" => "Rahul", "grade" => 78],
    ["name" => "Priya", "grade" => 92],
];

// Give everyone 2 bonus points
$students[0]["grade"] += 2;
$students[1]["grade"] += 2;

foreach ($students as $student) {
    echo $student["name"] . ": " . $student["grade"] . "\n";
}
?>
Output
Rahul: 80
Priya: 94
foreach Copies Values by Default

foreach ($students as $student) gives you a copy of each row, so changing $student inside the loop will not affect the original $students array. To modify rows while looping, either use the index (foreach ($students as $i => $student) then update $students[$i][...]) or loop by reference with &$student.

Common Mistakes

Avoid These Mistakes
  • Trying to modify data through a foreach copy and expecting the original array to change.
  • Mixing up the outer index and inner key order, e.g. writing $data["name"][0] instead of $data[0]["name"].
  • Assuming every row has exactly the same keys without checking — accessing a missing key triggers a warning.
  • Over-nesting arrays several levels deep when a simpler, flatter structure (or an object) would be clearer.

Best Practices

  • Keep the same set of keys consistent across every row of a multidimensional array.
  • Use foreach ($rows as $index => $row) when you need both a row number and its data.
  • Use isset() or array_key_exists() before accessing a field that might be missing from some rows.
  • Consider using classes/objects instead of nested arrays once the structure grows complex enough to need methods or validation.

Frequently Asked Questions

How deep can a multidimensional array go?

PHP does not impose a strict limit, but readability suffers quickly beyond two or three levels of nesting. At that point, restructuring the data or using objects is usually a better approach.

What is the difference between a multidimensional array and an object?

A multidimensional array of associative arrays can represent the same data as an array of objects, but objects can also carry behavior (methods), enforce structure, and offer better tooling support as a project grows.

Can I sort a multidimensional array by a specific field, like grade?

Yes, using usort() with a custom comparison function that compares the desired field, such as usort($students, fn($a, $b) => $b["grade"] <=> $a["grade"]) to sort by grade descending.

How do I count how many rows are in a multidimensional array?

count($students) returns the number of top-level elements (rows), the same as with any other array.

Can I loop over a multidimensional array without knowing the field names in advance?

Yes — a nested foreach ($row as $field => $value) loop works even if you do not know the keys ahead of time, which is useful for generic reporting code.

Key Takeaways

  • A multidimensional array is an array whose elements are themselves arrays.
  • They are ideal for representing tabular, record-like data such as a list of students or products.
  • Nested values are accessed by chaining keys, like $data[0]['name'].
  • Nested foreach loops (or index-based access to known fields) let you process every row and field.
  • foreach gives you a copy of each row by default, so use the index or a reference to modify the original data.

Summary

Multidimensional arrays let you model structured, tabular data directly in PHP, without needing a database or external file for small, simple collections.

In this lesson, you learned what multidimensional arrays are, how to access and modify nested values, how to loop over them with nested foreach loops, and worked through a complete student-report example. Next, you will learn how to control your program's flow using conditional statements.

Lesson 21 Completed
  • You understand what a multidimensional array represents.
  • You can access and modify deeply nested values.
  • You can loop over rows and fields using nested foreach.
  • You built a small, complete student report from structured data.
Next Lesson →

Conditional Statements