Back to course

Multi-dimensional Arrays

PHP: The Complete 0 to Hero Bootcamp

23. Multi-dimensional Arrays

A multi-dimensional array is an array that contains one or more arrays inside it. This structure is perfect for storing tabular data, hierarchical data, or complex configuration settings.

Creating a 2D Array

Consider an array storing information about employees, where each employee is represented by an associative array.

php

<?php $employees = [ [ 'id' => 1, 'name' => 'Sarah Connor', 'dept' => 'HR' ], [ 'id' => 2, 'name' => 'Kyle Reese', 'dept' => 'IT' ], [ 'id' => 3, 'name' => 'T-800', 'dept' => 'Security' ] ]; ?>

Accessing Elements

You chain the keys/indices. The first bracket selects the inner array (the row), and the second bracket selects the specific value within that inner array (the column).

php

<?php // Get the name of the second employee (index 1) echo "Employee 2 Name: " . $employees[1]['name']; // Output: Kyle Reese // Change the department of the first employee (index 0) $employees[0]['dept'] = 'Management'; echo "<br>Sarah's new department: " . $employees[0]['dept']; ?>

Iterating Multi-dimensional Arrays

We typically use nested foreach loops.

php

<?php echo "<h2>Employee List:</h2>"; foreach ($employees as $employee) { echo "Employee ID: " . $employee['id'] . ", Name: " . $employee['name'] . "<br>"; } ?>