Multidimensional Arrays in PHP Practice Questions with Solutions

Introduction

Multidimensional arrays in PHP allow you to store multiple arrays inside a single array. They are useful for organizing structured data such as employee records, student marks, product details, and sales reports. In this tutorial, you will learn to create, access, update, search, and manage nested arrays through practical PHP examples.

Question 1: Create a Two-Dimensional Indexed Array

Problem Statement

Create a two-dimensional indexed array containing the names of five students and their courses. Display the complete array using print_r().

PHP Solution

<?php
$students = [
    ["Rahul", "PHP"],
    ["Priya", "Python"],
    ["Amit", "Java"],
    ["Neha", "JavaScript"],
    ["Rohit", "C++"]
];

print_r($students);
?>

Sample Output

Array
(
    [0] => Array
        (
            [0] => Rahul
            [1] => PHP
        )

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

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

    [3] => Array
        (
            [0] => Neha
            [1] => JavaScript
        )

    [4] => Array
        (
            [0] => Rohit
            [1] => C++
        )
)

Explanation

  • $students contains five inner arrays.
  • Each inner array stores a student’s name and course.
  • The first index identifies the student record.
  • The second index identifies the value inside that record.
  • print_r() displays the complete multidimensional array.

Concepts Covered

  • Multidimensional array creation
  • Two-dimensional indexed arrays
  • Nested arrays
  • print_r() function

Question 2: Access Elements from a Two-Dimensional Array

Problem Statement

Create a two-dimensional array containing employee names and departments. Display the name and department of the second and fourth employees.

PHP Solution

<?php
$employees = [
    ["Rahul", "IT"],
    ["Priya", "HR"],
    ["Amit", "Sales"],
    ["Neha", "Finance"],
    ["Rohit", "Marketing"]
];

echo "Second Employee: " . $employees[1][0] . "\n";
echo "Department: " . $employees[1][1] . "\n\n";

echo "Fourth Employee: " . $employees[3][0] . "\n";
echo "Department: " . $employees[3][1];
?>

Sample Output

Second Employee: Priya
Department: HR

Fourth Employee: Neha
Department: Finance

Explanation

  • $employees[1] accesses the second employee’s inner array.
  • $employees[1][0] accesses that employee’s name.
  • $employees[1][1] accesses the department.
  • Similarly, $employees[3] accesses the fourth employee’s record.
  • Both indexes start from 0.

Concepts Covered

  • Accessing multidimensional array elements
  • Nested array indexes
  • Two-dimensional array navigation

Question 3: Create an Associative Multidimensional Array

Problem Statement

Create an associative multidimensional array containing three employee records. Store each employee’s ID, name, department, and salary. Display the complete array.

PHP Solution

<?php
$employees = [
    "emp1" => [
        "id" => 101,
        "name" => "Rahul",
        "department" => "IT",
        "salary" => 45000
    ],
    "emp2" => [
        "id" => 102,
        "name" => "Priya",
        "department" => "HR",
        "salary" => 42000
    ],
    "emp3" => [
        "id" => 103,
        "name" => "Amit",
        "department" => "Sales",
        "salary" => 40000
    ]
];

print_r($employees);
?>

Sample Output

Array
(
    [emp1] => Array
        (
            [id] => 101
            [name] => Rahul
            [department] => IT
            [salary] => 45000
        )

    [emp2] => Array
        (
            [id] => 102
            [name] => Priya
            [department] => HR
            [salary] => 42000
        )

    [emp3] => Array
        (
            [id] => 103
            [name] => Amit
            [department] => Sales
            [salary] => 40000
        )
)

Explanation

  • The main array uses employee keys such as emp1, emp2, and emp3.
  • Each employee key contains another associative array.
  • Inner arrays store employee information using named keys.
  • This structure makes related employee information easy to organize.

Concepts Covered

  • Associative multidimensional arrays
  • Nested associative arrays
  • Key-value pairs
  • Employee record management

Question 4: Access Nested Associative Array Values

Problem Statement

Using the employee array below, display the name, department, and salary of employee emp2.

PHP Solution

<?php
$employees = [
    "emp1" => [
        "name" => "Rahul",
        "department" => "IT",
        "salary" => 45000
    ],
    "emp2" => [
        "name" => "Priya",
        "department" => "HR",
        "salary" => 42000
    ],
    "emp3" => [
        "name" => "Amit",
        "department" => "Sales",
        "salary" => 40000
    ]
];

echo "Employee Name: " . $employees["emp2"]["name"] . "\n";
echo "Department: " . $employees["emp2"]["department"] . "\n";
echo "Salary: ₹" . $employees["emp2"]["salary"];
?>

Sample Output

Employee Name: Priya
Department: HR
Salary: ₹42000

Explanation

  • $employees["emp2"] accesses the second employee’s record.
  • ["name"] retrieves the employee’s name.
  • ["department"] retrieves the department.
  • ["salary"] retrieves the salary.
  • Multiple keys are used to access nested values.

Concepts Covered

  • Nested key access
  • Associative multidimensional arrays
  • Accessing employee records

Question 5: Update Values in a Multidimensional Array

Problem Statement

Create a multidimensional array containing product details. Update the price of the second product from ₹1,200 to ₹1,500 and its stock quantity from 25 to 40.

PHP Solution

<?php
$products = [
    [
        "name" => "Keyboard",
        "price" => 1200,
        "stock" => 25
    ],
    [
        "name" => "Mouse",
        "price" => 800,
        "stock" => 30
    ],
    [
        "name" => "Monitor",
        "price" => 12000,
        "stock" => 10
    ]
];

$products[1]["price"] = 1500;
$products[1]["stock"] = 40;

print_r($products);
?>

Sample Output

Array
(
    [0] => Array
        (
            [name] => Keyboard
            [price] => 1200
            [stock] => 25
        )

    [1] => Array
        (
            [name] => Mouse
            [price] => 1500
            [stock] => 40
        )

    [2] => Array
        (
            [name] => Monitor
            [price] => 12000
            [stock] => 10
        )
)

Explanation

  • $products[1] accesses the second product.
  • ["price"] identifies its price.
  • The price is updated to 1500.
  • The stock quantity is updated to 40.
  • Other product details remain unchanged.

Concepts Covered

  • Updating nested array values
  • Accessing inner arrays
  • Modifying product records

Question 6: Add a New Record to a Multidimensional Array

Problem Statement

Create a multidimensional array containing two student records. Add a third student with their roll number, name, and course using the [] operator.

PHP Solution

<?php
$students = [
    [
        "roll_no" => 1,
        "name" => "Rahul",
        "course" => "PHP"
    ],
    [
        "roll_no" => 2,
        "name" => "Priya",
        "course" => "Python"
    ]
];

$students[] = [
    "roll_no" => 3,
    "name" => "Amit",
    "course" => "Java"
];

print_r($students);
?>

Sample Output

Array
(
    [0] => Array
        (
            [roll_no] => 1
            [name] => Rahul
            [course] => PHP
        )

    [1] => Array
        (
            [roll_no] => 2
            [name] => Priya
            [course] => Python
        )

    [2] => Array
        (
            [roll_no] => 3
            [name] => Amit
            [course] => Java
        )
)

Explanation

  • Initially, the array contains two student records.
  • $students[] adds a new inner array.
  • The new student receives the next numeric index, 2.
  • The new record contains three key-value pairs.

Concepts Covered

  • Adding nested arrays
  • Appending records
  • Associative arrays inside indexed arrays

Question 7: Remove a Record from a Multidimensional Array

Problem Statement

Create a multidimensional array containing four product records. Remove the third product using unset() and display the remaining records.

PHP Solution

<?php
$products = [
    ["id" => 101, "name" => "Laptop"],
    ["id" => 102, "name" => "Keyboard"],
    ["id" => 103, "name" => "Mouse"],
    ["id" => 104, "name" => "Monitor"]
];

unset($products[2]);

print_r($products);
?>

Sample Output

Array
(
    [0] => Array
        (
            [id] => 101
            [name] => Laptop
        )

    [1] => Array
        (
            [id] => 102
            [name] => Keyboard
        )

    [3] => Array
        (
            [id] => 104
            [name] => Monitor
        )
)

Explanation

  • $products[2] refers to the third product.
  • unset() removes the complete inner array at index 2.
  • The remaining product records are preserved.
  • The numeric indexes are not automatically reset.

Concepts Covered

  • Removing nested arrays
  • unset() function
  • Multidimensional array indexes

Question 8: Display All Records Using Nested foreach Loops

Problem Statement

Create a multidimensional array containing three students and their marks in three subjects. Use nested foreach loops to display all student records.

PHP Solution

<?php
$students = [
    "Rahul" => [
        "English" => 85,
        "Maths" => 90,
        "Science" => 88
    ],
    "Priya" => [
        "English" => 92,
        "Maths" => 95,
        "Science" => 91
    ],
    "Amit" => [
        "English" => 78,
        "Maths" => 82,
        "Science" => 80
    ]
];

foreach ($students as $name => $subjects) {

    echo "Student: " . $name . "\n";

    foreach ($subjects as $subject => $marks) {
        echo $subject . ": " . $marks . "\n";
    }

    echo "\n";
}
?>

Sample Output

Student: Rahul
English: 85
Maths: 90
Science: 88

Student: Priya
English: 92
Maths: 95
Science: 91

Student: Amit
English: 78
Maths: 82
Science: 80

Explanation

  • The outer foreach loop accesses each student’s record.
  • $name stores the student name.
  • $subjects stores the student’s inner array.
  • The inner foreach loop accesses each subject and its marks.
  • Nested loops make it possible to display all records.

Concepts Covered

  • Nested foreach loops
  • Multidimensional array traversal
  • Accessing nested keys and values

Question 9: Calculate Total and Average Marks of Each Student

Problem Statement

Create a multidimensional array containing three students and their marks in three subjects. Calculate and display the total and average marks for each student.

PHP Solution

<?php
$students = [
    "Rahul" => [
        "English" => 80,
        "Maths" => 90,
        "Science" => 85
    ],
    "Priya" => [
        "English" => 90,
        "Maths" => 95,
        "Science" => 92
    ],
    "Amit" => [
        "English" => 75,
        "Maths" => 80,
        "Science" => 85
    ]
];

foreach ($students as $name => $marks) {

    $total = array_sum($marks);
    $average = $total / count($marks);

    echo "Student: " . $name . "\n";
    echo "Total Marks: " . $total . "\n";
    echo "Average Marks: " . number_format($average, 2) . "\n\n";
}
?>

Sample Output

Student: Rahul
Total Marks: 255
Average Marks: 85.00

Student: Priya
Total Marks: 277
Average Marks: 92.33

Student: Amit
Total Marks: 240
Average Marks: 80.00

Explanation

  • Each student has an inner array containing three subject marks.
  • array_sum() calculates the total of the marks.
  • count() returns the number of subjects.
  • The average is calculated by dividing total marks by the subject count.
  • number_format() displays the average up to two decimal places.

Concepts Covered

  • Multidimensional array calculations
  • array_sum() function
  • count() function
  • Nested array traversal

Question 10: Search for an Employee in a Multidimensional Array

Problem Statement

Create a multidimensional array containing employee IDs, names, and departments. Search for employee ID 103 and display the matching employee’s details. If the employee is not found, display an appropriate message.

PHP Solution

<?php
$employees = [
    [
        "id" => 101,
        "name" => "Rahul",
        "department" => "IT"
    ],
    [
        "id" => 102,
        "name" => "Priya",
        "department" => "HR"
    ],
    [
        "id" => 103,
        "name" => "Amit",
        "department" => "Sales"
    ],
    [
        "id" => 104,
        "name" => "Neha",
        "department" => "Finance"
    ]
];

$searchId = 103;
$found = false;

foreach ($employees as $employee) {

    if ($employee["id"] == $searchId) {

        echo "Employee Found!\n";
        echo "ID: " . $employee["id"] . "\n";
        echo "Name: " . $employee["name"] . "\n";
        echo "Department: " . $employee["department"];

        $found = true;
        break;
    }
}

if (!$found) {
    echo "Employee Not Found.";
}
?>

Sample Output

Employee Found!
ID: 103
Name: Amit
Department: Sales

Explanation

  • $searchId stores the employee ID to find.
  • The foreach loop checks each employee record.
  • The if condition compares the employee ID with the search ID.
  • When a matching record is found, its details are displayed.
  • $found tracks whether a matching employee exists.
  • break stops the loop after finding the employee.

Concepts Covered

  • Searching multidimensional arrays
  • foreach loop
  • Conditional statements
  • break statement
  • Searching employee records

Key Takeaways

  • Multidimensional arrays contain one or more arrays inside another array.
  • A two-dimensional array contains arrays inside a main array.
  • You can combine indexed and associative arrays.
  • Use multiple indexes or keys to access nested values.
  • Use [] to add new records.
  • Use unset() to remove nested elements.
  • Nested foreach loops help display multidimensional data.
  • Use array_sum() and count() to calculate totals and averages.
  • Multidimensional arrays are useful for managing employee, student, product, and sales records.

Frequently Asked Questions (FAQs)

1. What is a multidimensional array in PHP?

A multidimensional array is an array that contains one or more arrays as its elements. It allows you to organize related information in a structured format.

2. How do you create a two-dimensional array in PHP?

You can create a two-dimensional array by placing multiple arrays inside one main array.

$students = [
    ["Rahul", 85],
    ["Priya", 90],
    ["Amit", 78]
];

3. How do you access an element in a multidimensional array?

Use multiple indexes to access nested elements.

echo $students[0][1];

Output: 85

4. What is the difference between a one-dimensional and a multidimensional array?

A one-dimensional array stores values in a single list, while a multidimensional array stores other arrays inside the main array.

5. Can a multidimensional array contain associative arrays?

Yes. You can use named keys inside nested arrays to store structured information such as employee names, salaries, and departments.

6. How do you add a new record to a multidimensional array?

Use the [] operator to append a new inner array.

$students[] = ["Neha", 88];

7. How do you remove an element from a multidimensional array?

Use unset() with the required index or key.

unset($students[1]);

8. Why are nested foreach loops used in multidimensional arrays?

Nested foreach loops allow you to access the main array and its inner arrays. They are useful for displaying all records and their individual values.

9. Can a PHP multidimensional array have more than two dimensions?

Yes. PHP arrays can contain arrays nested inside other arrays across multiple levels. For example, you can organize company records by department, employee, and employee details.

10. Where are multidimensional arrays used in real-world PHP projects?

They are commonly used to manage student marks, employee records, product catalogs, shopping cart items, sales reports, and data retrieved from databases or APIs.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top