Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 147 ยท Arrays

Multidimensional Arrays

Work with arrays of arrays in PHP - tables of records, grids and matrices, deep access and updates, nested loops, array_column, indexing by ID and safe lookups.

An array value can be another array. That simple fact lets you model almost any data: a list of users where each user is an associative array, a chessboard as rows of squares, a menu with nested submenus, or a decoded JSON response several levels deep. Arrays that contain arrays are called multidimensional (or nested) arrays.

This lesson focuses on the two shapes you'll meet constantly: tables of records (a list of rows with the same keys, exactly what a database query returns) and grids (rows and columns of values). You'll read and update deep values, loop over nested data, extract columns with array_column(), index records by ID and avoid the warnings that missing levels cause. It assumes you're comfortable with Arrays and Associative Arrays.

A table of records

The most common nested shape is a list of associative arrays. Each inner array is one record, and all records share the same keys:

PHP A list of records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read $employees[1]['name'] from left to right: first take element 1 of the outer list (Bruno's record), then take its 'name'. Each extra pair of brackets goes one level deeper.

This is exactly the shape you get from PDOStatement::fetchAll(PDO::FETCH_ASSOC) in PDO Basics and from json_decode($json, true) on a JSON array of objects (JSON), so the techniques here apply directly to real data.

Grids and matrices

A grid is a list of rows, where each row is a list of values. $grid[$row][$column] reads one cell. Nested foreach loops visit every cell: the outer loop walks the rows, the inner loop walks the cells in the current row.

PHP A grid with nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You can also build a grid with nested for loops. Here's a multiplication table, where each cell is computed from its row and column number:

PHP Building a grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The line $table[$row][$col] = โ€ฆ creates the inner array automatically the first time a row number is used. This "autovivification" only happens when writing; reading $table[9][9] would warn that key 9 doesn't exist.

Changing nested values

Assignment works at any depth: $employees[2]['salary'] = 70000; changes one field of one record. Changing every record in a loop needs care, because foreach gives you a copy of each row. Writing to that copy changes nothing in the original array:

PHP Updating rows in a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Writing back through $products[$index] is the safest habit. The by-reference version works too, but you must unset() the reference after the loop, or a later loop reusing $product would overwrite the last row (the dangling reference bug from foreach Loops). A third option is building a new array with array_map(), covered in array_map, array_filter and array_reduce.

Extracting columns with array_column

array_column($rows, $columnKey, $indexKey = null) pulls one field out of every record. It's one of the most useful functions for table data:

  • array_column($rows, 'name') returns a list of names.
  • array_column($rows, 'name', 'id') returns names keyed by ID.
  • array_column($rows, null, 'id') returns the whole records, keyed by ID.
PHP array_column in three forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Indexing by ID turns a slow search ("loop until you find id 12") into a single lookup, which matters when you need to match records from two lists. Rows that lack the column are skipped. array_column() also works on arrays of objects, reading their public properties.

Combining two tables

A common real task: you have orders and customers in separate lists, and you want each order with its customer's name. Index one list by ID, then loop over the other. This is the same idea as a database join, done in PHP:

PHP Joining two lists by ID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The ?? fallback handles order A-103, whose customer doesn't exist in the list. When data comes from a real database, a SQL JOIN is usually the better tool; see Pagination, Search and Database Patterns.

Deep data and safe access

Nesting can go as deep as you like. Data decoded from a JSON API often has three or four levels, and some branches may be missing. Reading a missing level directly warns, and reading deeper into a null warns again. The ?? operator checks the whole path at once:

PHP Reading deep values safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

count($array, COUNT_RECURSIVE) counts the elements at every level, inner arrays included. It's mostly useful as a quick size check while debugging.

If you write $a['x']['y']['z'] ?? null in many places, give that path a name: a small function like userCity(array $response): ?string documents the structure and keeps the fallback logic in one spot. When the same nested shape appears all over your code, it's time for classes, introduced in Object-Oriented Programming in PHP.

Transposing and other grid tricks

Two built-ins handle common grid operations. array_map(null, ...$grid) transposes a grid (rows become columns), because array_map() with a null callback zips its array arguments together. array_sum() with array_column() totals one column, and array_column() with a numeric key extracts a column of a plain grid:

PHP Row totals, column totals and transposing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The array_values() call matters: spreading an array with string keys into a function call would pass them as named arguments instead of positional ones, and array_map() would fail with ArgumentCountError: array_map() expects at least 2 arguments, 1 given.

When nesting gets too deep

Nested arrays are flexible, but that flexibility has a cost. Nothing stops one record from having 'name' and another 'Name', every access needs a fallback, and readers have to guess the structure. Some guidelines:

  • Two levels (a table or a grid) are perfectly normal.
  • Beyond three levels, write down the shape in a PHPDoc comment, for example @param list<array{id: int, name: string}> $users, which static analysis tools understand (The PHP Type System in Depth).
  • When the same record shape is passed around many functions, replace it with a class or a readonly object (Readonly Properties and Immutable Objects).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given $m = [[1, 2], [3, 4], [5, 6]];, what is $m[2][0]?

    $m[2] is the third row, [5, 6], and index 0 of that row is 5.
  2. 2. What does array_column($rows, 'name', 'id') return?

    The second argument chooses the values, the third chooses the keys. Passing null as the second argument would return whole rows.
  3. 3. After foreach ($rows as $row) { $row['done'] = true; }, what happened to $rows?

    foreach copies each value into $row. Write back with $rows[$key][...] or iterate by reference (and unset the reference afterwards).
  4. 4. What does $data['a']['b']['c'] ?? 'none' do when $data has no key 'a'?

    The ?? operator checks the whole chain, so a missing level at any depth just produces the default.

Summary

  • A multidimensional array is an array whose values are arrays; each pair of brackets goes one level deeper, as in $rows[1]['name'].
  • Lists of associative arrays model tables of records, the same shape PDO and json_decode(โ€ฆ, true) return.
  • Grids use $grid[$row][$col]; nested loops visit every cell, and writing $a[$i][$j] = โ€ฆ creates missing inner arrays.
  • foreach gives copies of rows: update through $rows[$key][โ€ฆ], or by reference with unset() afterwards.
  • array_column() extracts a column, keys it by another column, or (with null) indexes whole records by ID.
  • ?? makes deep reads safe; count($a, COUNT_RECURSIVE) counts every level.
  • array_map(null, ...$grid) transposes a grid.
  • Document deep shapes with PHPDoc, and switch to classes when one shape is used everywhere.

Next: Array Functions, a tour of the built-in functions for adding, removing, searching, slicing and combining arrays.