Multidimensional arrays help you store data in a table or grid form, like rows and columns. They let you organize related data inside other arrays.
Multidimensional arrays in PHP
<?php // Define a 2D array (array of arrays) $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Access element in row 2, column 3 $value = $matrix[1][2]; ?>
Each element of the main array is itself an array.
Use two sets of square brackets to access elements: first for row, second for column.
<?php // Empty multidimensional array $empty = []; ?>
<?php // 2D array with one row and one column $single = [[42]]; ?>
<?php // Access first element of second row $colors = [ ['red', 'green'], ['blue', 'yellow'] ]; $firstColorSecondRow = $colors[1][0]; ?>
<?php // 3D array example $box = [ [ [1, 2], [3, 4] ], [ [5, 6], [7, 8] ] ]; ?>
This program creates a 2D array to represent seats in rows. It prints the seating chart, changes one name, then prints the updated chart.
<?php // Create a 2D array representing a small seating chart $seatingChart = [ ['Alice', 'Bob', 'Charlie'], ['David', 'Eva', 'Frank'], ['Grace', 'Hank', 'Ivy'] ]; // Print original seating chart echo "Original seating chart:\n"; foreach ($seatingChart as $rowIndex => $row) { echo "Row " . ($rowIndex + 1) . ": "; foreach ($row as $seat) { echo $seat . " "; } echo "\n"; } // Change the seat of 'Eva' to 'Eve' $seatingChart[1][1] = 'Eve'; // Print updated seating chart echo "\nUpdated seating chart:\n"; foreach ($seatingChart as $rowIndex => $row) { echo "Row " . ($rowIndex + 1) . ": "; foreach ($row as $seat) { echo $seat . " "; } echo "\n"; } ?>
Accessing elements is fast, O(1) time, because you use direct indexes.
Multidimensional arrays use more memory because they store arrays inside arrays.
Common mistake: forgetting that each element is an array, so you must use multiple brackets to access nested data.
Use multidimensional arrays when you need to group related data in rows and columns. For simple lists, use one-dimensional arrays.
Multidimensional arrays store data in nested arrays, like tables or grids.
Use multiple square brackets to access or change elements.
They help organize complex data clearly and access it quickly.