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
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
Sarah's new department: " . $employees[0]['dept']; ?>Iterating Multi-dimensional Arrays
We typically use nested foreach loops.
php
Employee List:"; foreach ($employees as $employee) { echo "Employee ID: " . $employee['id'] . ", Name: " . $employee['name'] . ""; } ?>