0
0
PHPprogramming~5 mins

Multidimensional arrays in PHP

Choose your learning style9 modes available
Introduction

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.

To store a list of students with their grades in different subjects.
To represent a chessboard with pieces on each square.
To keep track of a calendar with events for each day and time.
To manage a menu with categories and items inside each category.
Syntax
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.

Examples
This is an empty multidimensional array with no elements.
PHP
<?php
// Empty multidimensional array
$empty = [];
?>
Array with only one element inside a nested array.
PHP
<?php
// 2D array with one row and one column
$single = [[42]];
?>
Gets 'blue' from the second row, first column.
PHP
<?php
// Access first element of second row
$colors = [
    ['red', 'green'],
    ['blue', 'yellow']
];
$firstColorSecondRow = $colors[1][0];
?>
Array inside array inside array, like layers of boxes.
PHP
<?php
// 3D array example
$box = [
    [
        [1, 2],
        [3, 4]
    ],
    [
        [5, 6],
        [7, 8]
    ]
];
?>
Sample Program

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
<?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";
}
?>
OutputSuccess
Important Notes

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.

Summary

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.