Lesson 24 of 50 – PHP Multidimensional Arrays
48%

PHP Multidimensional Arrays

A multidimensional array is an array that contains one or more arrays as its elements. It is useful for storing structured data such as student records, employee details, product lists, and marksheets.

1. What Is a Multidimensional Array?

A normal array stores a list of values. A multidimensional array can store multiple arrays inside a parent array.

<?php
$students = [
    ["Rahul", 20, "PHP"],
    ["Amit", 21, "Java"],
    ["Priya", 19, "Python"]
];

print_r($students);
?>
Output:
Array
(
    [0] => Array
        (
            [0] => Rahul
            [1] => 20
            [2] => PHP
        )

    [1] => Array
        (
            [0] => Amit
            [1] => 21
            [2] => Java
        )

    [2] => Array
        (
            [0] => Priya
            [1] => 19
            [2] => Python
        )
)

Each inner array represents one student and contains that student's name, age, and course.

2. Creating a Two-Dimensional Array

A two-dimensional array can be visualized as rows and columns, similar to a table.

<?php
$marks = [
    [80, 85, 90],
    [75, 88, 92],
    [90, 95, 89]
];

print_r($marks);
?>
Array structure:
Student Subject 1 Subject 2 Subject 3
Student 1 80 85 90
Student 2 75 88 92
Student 3 90 95 89

Each outer index identifies a row, and each inner index identifies a value within that row.

3. Accessing Elements in a Multidimensional Array

Use multiple square-bracket indexes to access values inside nested indexed arrays.

<?php
$students = [
    ["Rahul", 20, "PHP"],
    ["Amit", 21, "Java"],
    ["Priya", 19, "Python"]
];

echo $students[0][0];
echo "<br>";
echo $students[0][2];
echo "<br>";
echo $students[1][0];
echo "<br>";
echo $students[2][2];
?>
Output:
Rahul
PHP
Amit
Python

For example, $students[1][0] accesses the first value in the second inner array.

4. Using Associative Arrays Inside a Multidimensional Array

You can use named keys inside each nested array to make records easier to understand.

<?php
$students = [
    [
        "name" => "Rahul",
        "age" => 20,
        "course" => "PHP"
    ],
    [
        "name" => "Amit",
        "age" => 21,
        "course" => "Java"
    ],
    [
        "name" => "Priya",
        "age" => 19,
        "course" => "Python"
    ]
];

echo $students[0]["name"];
echo "<br>";
echo $students[1]["course"];
echo "<br>";
echo $students[2]["age"];
?>
Output:
Rahul
Java
19

This structure is useful when every record has properties such as name, age, course, or email.

5. Adding, Updating, and Removing Elements

You can update or add values inside an inner array by using its keys.

<?php
$students = [
    [
        "name" => "Rahul",
        "marks" => 80
    ],
    [
        "name" => "Amit",
        "marks" => 75
    ]
];

// Update marks
$students[0]["marks"] = 90;

// Add a new field
$students[0]["course"] = "PHP";

// Add another student
$students[] = [
    "name" => "Priya",
    "marks" => 95
];

// Remove a field
unset($students[1]["marks"]);

print_r($students);
?>

The first student's marks are updated, a course field is added, a new student is appended, and the marks field is removed from the second student.

Important: After using unset(), the remaining keys are not automatically renumbered.

6. Displaying a Multidimensional Array with Nested foreach

A foreach loop inside another foreach loop can display values from nested arrays.

<?php
$students = [
    ["Rahul", 20, "PHP"],
    ["Amit", 21, "Java"],
    ["Priya", 19, "Python"]
];

foreach ($students as $student) {
    foreach ($student as $value) {
        echo $value . " ";
    }

    echo "<br>";
}
?>
Output:
Rahul 20 PHP
Amit 21 Java
Priya 19 Python

The outer loop accesses each student record, and the inner loop displays the values within that record.

Display keys and values:

<?php
$students = [
    [
        "name" => "Rahul",
        "course" => "PHP"
    ],
    [
        "name" => "Amit",
        "course" => "Java"
    ]
];

foreach ($students as $index => $student) {
    echo "Student " . ($index + 1) . "<br>";

    foreach ($student as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }

    echo "<hr>";
}
?>
7. Displaying Data in an HTML Table

Multidimensional arrays can be used to generate HTML tables dynamically.

<?php
$students = [
    ["name" => "Rahul", "course" => "PHP", "marks" => 85],
    ["name" => "Amit", "course" => "Java", "marks" => 90],
    ["name" => "Priya", "course" => "Python", "marks" => 95]
];
?>

<table border="1" cellpadding="8">
    <tr>
        <th>Name</th>
        <th>Course</th>
        <th>Marks</th>
    </tr>

    <?php foreach ($students as $student): ?>
        <tr>
            <td>
                <?= htmlspecialchars($student["name"], ENT_QUOTES, "UTF-8") ?>
            </td>
            <td>
                <?= htmlspecialchars($student["course"], ENT_QUOTES, "UTF-8") ?>
            </td>
            <td>
                <?= htmlspecialchars((string) $student["marks"], ENT_QUOTES, "UTF-8") ?>
            </td>
        </tr>
    <?php endforeach; ?>
</table>
Output:
Name Course Marks
Rahul PHP 85
Amit Java 90
Priya Python 95

htmlspecialchars() helps prevent HTML markup in text values from being interpreted as HTML. It is a useful habit when displaying user-provided data.

8. Calculating Total and Average Marks

We can calculate each student's total and average using values stored in a multidimensional array.

<?php
$students = [
    [
        "name" => "Rahul",
        "marks" => [80, 85, 90]
    ],
    [
        "name" => "Amit",
        "marks" => [75, 88, 92]
    ],
    [
        "name" => "Priya",
        "marks" => [90, 95, 89]
    ]
];

foreach ($students as $student) {
    $total = array_sum($student["marks"]);
    $subjects = count($student["marks"]);
    $average = $subjects > 0 ? $total / $subjects : 0;

    echo "Name: " . $student["name"] . "<br>";
    echo "Total: " . $total . "<br>";
    echo "Average: " . number_format($average, 2) . "<br>";
    echo "<hr>";
}
?>
Output:
Name: Rahul
Total: 255
Average: 85.00

Name: Amit
Total: 255
Average: 85.00

Name: Priya
Total: 274
Average: 91.33

array_sum() adds the marks, while count() determines the number of subjects. number_format() displays the average with two decimal places.

9. Three-Dimensional Arrays

An array can contain another array that contains additional arrays. This structure is called a multidimensional array with three levels when three indexes are used to access a value.

<?php
$school = [
    "Class 10" => [
        "Section A" => [
            "Rahul",
            "Amit"
        ],
        "Section B" => [
            "Priya",
            "Neha"
        ]
    ],
    "Class 12" => [
        "Section A" => [
            "Ravi",
            "Pooja"
        ]
    ]
];

echo $school["Class 10"]["Section A"][0];
echo "<br>";
echo $school["Class 10"]["Section B"][1];
echo "<br>";
echo $school["Class 12"]["Section A"][0];
?>
Output:
Rahul
Neha
Ravi

The first key selects a class, the second key selects a section, and the numeric index selects a student.

Practice Assignments
  1. Create a two-dimensional array containing three students and their marks in three subjects.
  2. Display the name and course of the second student.
  3. Add a new student record to an existing array.
  4. Update one student's marks and remove a field from another student.
  5. Display all student records using nested foreach loops.
  6. Generate an HTML table from an array of student records.
  7. Calculate the total and average marks of every student.
  8. Create a three-dimensional array containing classes, sections, and student names.

🧠 Quick Quiz

1. What is a multidimensional array?




2. How do you access the first element of the second inner array in $data?




3. Which function calculates the sum of numeric values in an array?