Multidimensional Array in PHP

As discussed earlier, an array in PHP can store both numbers as well as string values. Additionally, it can also store other arrays as its elements. Such an array is known as a multidimensional array or an array of arrays.

A multidimensional array in PHP is an array containing one or more arrays as its elements. It allows you to represent complex data in a structured way, organizing it in rows and columns or even more complex structures, such as matrices or higher levels of nesting.

For example, suppose we want to store information about students, including their name, class, and marks in different subjects. We will represent each student as an associative array with keys such as “name”, “class”, and “marks”. We will store these student arrays within a parent array, which makes a multidimensional array.

<?php
$students = [
      [
        "name" => "Alice",
        "class" => 10,
        "marks" => ["Math" => 90, "Science" => 85, "English" => 88]
      ],
      [
        "name" => "Bob",
        "class" => 12,
        "marks" => ["Math" => 78, "Science" => 82, "English" => 80]
      ],
      [
        "name" => "Charlie",
        "class" => 11,
        "marks" => ["Math" => 88, "Science" => 90, "English" => 92]
      ]
];
?>

In this example, we have represented each student as an associative array with keys “name”, “class”, and “marks”. The “marks” key itself is an associative array storing subject names as keys and corresponding marks as values. The $students array is a parent array holding all the individual student arrays.

We can visualize this array as a table with rows and columns as:

NameClassGrades
Alice10Math: 90, Science: 85, English: 88
Bob12Math: 78, Science: 82, English: 80
Charlie11Math: 88, Science: 90, English: 92

In this way, you can organize hierarchical data like student records or similar data sets.

Types of Multidimensional Array in PHP


There are mainly two types of multidimensional arrays in PHP, categorized based on the number of nested arrays within them. They are:

  • Two-dimensional array
  • Three-dimensional array

Two-dimensional Array

A two-dimensional array is the simplest form of a multidimensional array in PHP, which represents data in rows and columns, like a table. In the two-dimensional array, each element of the outer array is a one-dimensional array.

Each inner array represents a row, and each element within the inner array represents a column. Two-dimensional array is commonly used for representing tables of data, matrices for mathematical operations, and other data structures requiring rows and columns.

Syntax to Create Two-dimensional Array

The general syntax to create a two-dimensional array in PHP is as follows:

$array_name = [
    [element1, element2], // First inner array
    [element3, element4], // Second inner array
    [element5, element6] // Third inner array
];

In the above syntax of two-dimensional array, $array_name is a variable name that holds an array of arrays. The equal sign (=) assigns the array to the variable. The square brackets ([ ]) are used to define the array in PHP.

Example 1:

// Creating two-dimensional array.
$twoDimensionalArray = [
    ["Apple", "Red"], // First inner array.
    ["Banana", "Yellow"], // Second inner array.
    ["Grapes", "Green"] // Third inner array.
];

In this example, “Apple”, “Red” are elements in the first inner array (i.e. first row). “Banana”, “Yellow” are elements in the second inner array (i.e. second row). Similarly, “Grapes”, “Green” are elements in the third inner array.

Three-dimensional Array

A three-dimensional array in PHP is an array where each element is an array containing arrays of arrays. It is used to represent more complex hierarchical or structured data. The general syntax for creating a three-dimensional array in PHP is as follows:

$arrayName = [
      [
        [Element1, Element2, Element3],
        [Element4, Element5, Element6]
      ],
      [
        [Element7, Element8, Element9],
        [Element10, Element11, Element12]
      ]
];

In the above syntax of three-dimensional array, the top-level array contains two elements. However, it may also contain more than two elements as per your need. Each element of the top-level array is itself a two-dimensional array. Each element of two-dimensional array contains a one-dimensional array that represent rows of data.


Example 2: Let’s take an example in which we will represent a 3D array of a library. Suppose we have a library with two floors. Each floor has two shelves, and each shelf contains two books.

$library = [
   // Floor 1
     [
     // Shelf 1
        ["Book1", "Book2"],
     // Shelf 2
        ["Book3", "Book4"]
     ],
     // Floor 2
     [
     // Shelf 1
        ["Book5", "Book6"],
     // Shelf 2
        ["Book7", "Book8"]
     ]
];

In this example,

  • $library[0] refers to Floor 1.
  • $library[1] refers to Floor 2.
  • $library[0][0] refers to Shelf 1 on Floor 1.
  • $library[0][1] refers to Shelf 2 on Floor 1.
  • $library[1][1][1] refers to the Second Book on Shelf 2 of Floor 2.

Accessing Elements in a Multidimensional Array in PHP


To access elements in a multidimensional array in PHP, you will have to use multiple indices. The first index represents the outermost array, the second index refers to the first nested array, the third index refers to the second nested array, and so on.


Example 3: Write the PHP code for storing and accessing the basic information of employees using a multidimensional array.

<?php
// Creating two-dimensional array to store basic information of employees in a multidimensional array
$employees = [
    ["name" => "John", "age" => 28, "department" => "HR"],
    ["name" => "Alice", "age" => 25, "department" => "IT"],
    ["name" => "Mark", "age" => 30, "department" => "Finance"]
];

// Accessing specific elements of two-dimensional array.
echo "Name of employee1: " . $employees[0]["name"] . "\n";
echo "Age of employee2: " . $employees[1]["age"] . "\n";
echo "Department of employee3: " . $employees[2]["department"] . "\n";
?>

Example 4:

<?php
# Creating three-dimensional array.
$students = [
    [
      "name" => "Alice",
      "age" => 20,
      "marks" => ["Math" => 90, "Science" => 85, "English" => 88]
    ],
    [
      "name" => "Bob",
      "age" => 22,
      "marks" => ["Math" => 78, "Science" => 82, "English" => 80]
    ],
    [
      "name" => "Charlie",
      "age" => 21,
      "marks" => ["Math" => 88, "Science" => 90, "English" => 92]
    ]
];
// Accessing specific elements of three-dimensional array.
echo $students[0]["name"] . "\n";
echo $students[1]["marks"]["Science"] . "\n";
echo $students[2]["marks"]["English"];
?>
Output:
       Alice
       82
       92

Iterating over Multidimensional Arrays in PHP


You can iterate over elements of multidimensional array in PHP using foreach loop. This is the most easy method to iterate over the elements of multidimensional array in PHP. However, you can also use for loop to iterate it. So, let’s take an example on it.

Example 5:

<?php
# Creating two-dimensional array.
$employees = [
    ["name" => "John", "age" => 35, "department" => "HR"],
    ["name" => "Jane", "age" => 28, "department" => "Finance"],
    ["name" => "Mike", "age" => 32, "department" => "IT"]
];

// Iterating multidimensional array using foreach loop.
foreach ($employees as $employee) {
echo "Name: " . $employee["name"] . "\n";
echo "Age: " . $employee["age"] . "\n";
echo "Department: " . $employee["department"] . "\n";
echo "----------------------\n";
}
?>
Output:
      Name: John
      Age: 35
      Department: HR
      ----------------------
      Name: Jane
      Age: 28
      Department: Finance
      ----------------------
      Name: Mike
      Age: 32
      Department: IT
      ----------------------

In this example, we have created a 2D array named $employee where each element is an associative array containing key-value pairs. Then, we have used foreach loop to iterate over elements of multidimensional array. The foreach ($employees as $employee) loop extracts each inner array representing one employee from $employees.

Inside the loop, the keys of the associative array such as “name”, “age”, “department” are accessed using $employee[“key”]. At last, we have used the echo statement to print the values for each employee, followed by a line separator for readability.

Iterating Through Three-Dimensional Array

To iterate over elements of a three-dimensional array, you need to use nested foreach loops. The outer foreach loop iterates over the outer array, while the inner foreach loop iterates over each inner array.

Example 6:

<?php
// Creating a three-dimensional array.
$departments = [
     "HR" => [
                ["name" => "Alice", "age" => 32],
                ["name" => "Bob", "age" => 27]
     ],
     "IT" => [
                ["name" => "Charlie", "age" => 29],
                ["name" => "David", "age" => 33]
     ],
     "Finance" => [
                    ["name" => "Eve", "age" => 45],
                    ["name" => "Frank", "age" => 35]
     ]
];
// Iterating through the three-dimensional array.
foreach ($departments as $departmentName => $employees) {
   echo "Department: $departmentName\n";
  foreach ($employees as $employee) {
     foreach ($employee as $key => $value) {
        echo "$key: $value\n";
     }
     echo "\n";
  }
  echo "-----------------------\n";
}
?>
Output:
      Department: HR
      name: Alice
      age: 32

      name: Bob
      age: 27

      -----------------------
      Department: IT
      name: Charlie
      age: 29

      name: David
      age: 33

      -----------------------
      Department: Finance
      name: Eve
      age: 45

      name: Frank
      age: 35

      -----------------------

In this example, the outer foreach loop iterates over the main array named departments that hold department such as “HR”, “IT”, and “Finance”. Each department contains a list of employees. Therefore, the second foreach loop inside the outer loop iterates over the employees in each department. The innermost foreach loop iterates over the key-value pairs (such as name and age) of each employee.

Modifying Elements in Multidimensional Array in PHP


You can modify elements in multidimensional array just like you do in regular array. Simply reference the element you want to change and assign a new value to it. Let’s take an example on it.

Example 7:

<?php
$product = [
   [
     'name' => 'Product 1',
     'price' => '90.95',
     'category' => 'Category 1'
   ],
   [
     'name' => 'Product 2',
     'price' => '95.99',
     'category' => 'Category 2'
   ],
];
// Modifying an element in multidimensional array.
$product[0]['price'] = 75.99;
echo $product[0]['price'];
?>
Output:
       75.99

Adding New Element to Multidimensional Arrays in PHP


Adding a new element in multidimensional array is a very simple and straightforward in PHP. If you want to add a new element in an array, you can do like this as in the below example.

Example 8: Adding a new element in two-dimensional array

<?php
$product = [
    [
      'name' => 'Product 1',
      'price' => '90.95',
      'category' => 'Category 1'
    ],
    [
      'name' => 'Product 2',
      'price' => '95.99',
      'category' => 'Category 2'
    ],
];

// Adding a new element in multidimensional array.
$product[] = [
    'name' => 'Product 3',
    'price' => '75.99',
    'category' => 'Category 3'
];
// Print the updated array.
print_r($product);
?>
Output:
    Array
    (
      [0] => Array
          (
            [name] => Product 1
            [price] => 90.95
            [category] => Category 1
          )
      [1] => Array
          (
            [name] => Product 2
            [price] => 95.99
            [category] => Category 2
          )
      [2] => Array
          (
            [name] => Product 3
            [price] => 75.99
            [category] => Category 3
          )
     )

Example 9: Adding a new element in three-dimensional array

<?php
$departments = [
   "EC" => [
             ["name" => "Alice", "id" => 23214],
             ["name" => "Bob", "id" => 24535],
   ],
   "CS" => [
             ["name" => "Charlie", "id" => 28234],
             ["name" => "David", "id" => 35112],
   ],
];
// Add a new student to the IT department
$departments["CS"][] = ["name" => "Eve", "id" => 27234];

// Add a new department with students.
$departments["IT"] = [
    ["name" => "Frank", "id" => 41231],
    ["name" => "Grace", "id" => 32211],
];

// Print the updated array
print_r($departments);
?>
Output:
     Array
    (
      [EC] => Array
          (
            [0] => Array
                (
                    [name] => Alice
                    [id] => 23214
                )

            [1] => Array
                (
                    [name] => Bob
                    [id] => 24535
                )

          )

      [CS] => Array
          (
            [0] => Array
                (
                    [name] => Charlie
                    [id] => 28234
                )

            [1] => Array
                (
                    [name] => David
                    [id] => 35112
                )

            [2] => Array
                (
                    [name] => Eve
                    [id] => 27234
                )

          )

    [IT] => Array
        (
            [0] => Array
                (
                    [name] => Frank
                    [id] => 41231
                )

            [1] => Array
                (
                    [name] => Grace
                    [id] => 32211
                )
          )
   )

Best Practices for Working with Multidimensional Arrays


There are some key points to work with multidimensional array in PHP that you should keep in mind. They are as:

  • Always initialize arrays properly to avoid undefined index errors.
  • Always try to avoid deep nesting.
  • Use descriptive keys for associative arrays for better readability.
  • Always check if indices exist before accessing them.

In conclusion, multidimensional array is a powerful tool in PHP that allows you to structure complex data in a manageable and logical way. It is generally useful when you are working with groups of related data or representing hierarchical relationships.

You can use most of the built-in PHP functions to work with multidimensional array that you have used to work with indexed and associative arrays. However, some of them may generate unexpected results because they only operate on one-dimensional array. I hope that you will have understood the basic definition of multidimensional array in PHP and practiced all examples.