TExcelTAD
Home › PHP › PHP Multidimensional Arrays

PHP Multidimensional Arrays

A multidimensional array is simply an array whose values are themselves arrays. Two levels give you a table (rows and columns), three levels a cube, and so on. In practice you will mostly see two shapes:

  • a list of records — e.g. rows from a database, each an associative array;
  • a nested structure — e.g. decoded JSON with objects inside objects.

A grid of numbers

Use one pair of brackets per level: $grid[row][column].

php · try it yourself
<?php
$grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

echo 'Centre: ' . $grid[1][1] . PHP_EOL;
echo 'Bottom-right: ' . $grid[2][2] . PHP_EOL;

foreach ($grid as $row) {
    echo implode(' ', $row) . PHP_EOL;
}
Centre: 5
Bottom-right: 9
1 2 3
4 5 6
7 8 9

A list of records

This is the shape you will meet most often: an indexed array where each item is an associative array with the same keys.

php · try it yourself
<?php
$employees = [
    ['name' => 'Linh',  'team' => 'Design', 'salary' => 4200],
    ['name' => 'Oscar', 'team' => 'Dev',    'salary' => 5100],
    ['name' => 'Priya', 'team' => 'Dev',    'salary' => 5600],
];

printf("%-6s %-7s %6s\n", 'Name', 'Team', 'Salary');
foreach ($employees as $e) {
    printf("%-6s %-7s %6d\n", $e['name'], $e['team'], $e['salary']);
}

$total = array_sum(array_column($employees, 'salary'));
echo "Payroll: $total" . PHP_EOL;
echo 'Second person: ' . $employees[1]['name'] . PHP_EOL;
Name   Team    Salary
Linh   Design    4200
Oscar  Dev       5100
Priya  Dev       5600
Payroll: 14900
Second person: Oscar

Tip: array_column($rows, 'salary') pulls one "column" out of a list of records. Add a third argument to choose the keys: array_column($rows, 'salary', 'name') gives ['Linh' => 4200, …].

Building nested arrays step by step

You can assign deep into an array that does not exist yet — PHP creates the missing levels for you. This makes grouping data very easy.

php · try it yourself
<?php
$sales = [
    ['region' => 'North', 'month' => 'Jan', 'amount' => 120],
    ['region' => 'South', 'month' => 'Jan', 'amount' => 80],
    ['region' => 'North', 'month' => 'Feb', 'amount' => 95],
    ['region' => 'North', 'month' => 'Jan', 'amount' => 30],
];

$report = [];
foreach ($sales as $s) {
    $report[$s['region']][$s['month']] ??= 0;
    $report[$s['region']][$s['month']] += $s['amount'];
}

print_r($report);
Array
(
    [North] => Array
        (
            [Jan] => 150
            [Feb] => 95
        )

    [South] => Array
        (
            [Jan] => 80
        )

)

The ??= operator sets the value to 0 only if it does not exist yet, so the += that follows never reads a missing key.

Walking an unknown depth

When you do not know how deep the nesting goes, use a recursive function that calls itself for every sub-array:

php · try it yourself
<?php
$menu = [
    'File' => ['New', 'Open', 'Recent' => ['report.txt', 'notes.md']],
    'Edit' => ['Undo', 'Redo'],
];

function show(array $items, int $depth = 0): void
{
    foreach ($items as $key => $value) {
        $indent = str_repeat('  ', $depth);
        if (is_array($value)) {
            echo $indent . $key . PHP_EOL;
            show($value, $depth + 1);
        } else {
            echo $indent . '- ' . $value . PHP_EOL;
        }
    }
}

show($menu);
File
  - New
  - Open
  Recent
    - report.txt
    - notes.md
Edit
  - Undo
  - Redo

Modifying rows inside a loop

foreach works on a copy of each row. To change the original array, either write back through the key or loop by reference with &:

Approach Code
Write back with the key foreach ($rows as $i => $r) { $rows[$i]['vat'] = $r['price'] * 0.1; }
Loop by reference foreach ($rows as &$r) { $r['vat'] = $r['price'] * 0.1; } unset($r);

Note: After a by-reference loop, always unset($r). Otherwise $r still points at the last row, and reusing the name later silently overwrites it.

Test yourself

With $m = [[1, 2], [3, 4]];, what is $m[1][0]?

  1. 1
  2. 2
  3. 3
  4. 4

Which function extracts one field from every record in a list?

  1. array_keys()
  2. array_column()
  3. array_slice()
  4. array_flip()

Why call unset($r) after foreach ($rows as &$r)?

  1. To free all rows
  2. To break the reference so later code does not overwrite the last row
  3. It is required syntax
  4. To sort the array