Menu

PHP Multidimensional Arrays: Nested Arrays and Loops

A multidimensional array in PHP is an array whose elements are arrays, read with one bracket per level: $grid[1][2] or $users[0]['name']. Learn how to create nested arrays, read and change deep values, loop with nested foreach, build an HTML table, pull out a column and sort rows.

This page includes runnable editors - edit, run, and see output instantly.

A multidimensional array is an array whose elements are arrays. You read it with one pair of brackets per level: $grid[1][2] is row 1, column 2, and $users[0]['name'] is the name in the first record.

The second shape, a list of records with named fields, is the one you will meet most: it is what a database query, a decoded JSON response or a parsed CSV file usually gives you. Each record is an associative array.

Create nested arrays

Nesting can go as deep as you need and the levels can mix numeric and string keys. A config array is a common example: named sections, each holding settings or lists.

Add rows and nested values

$rows[] = [...] appends a whole row. $arr['key'][] = $value appends inside a nested list, and PHP creates the inner array the first time, so grouping values needs no setup.

Loop through a multidimensional array

Use one foreach per level. For a list of records, one loop is usually enough because you read the fields by name. For a grid, the inner loop walks the cells of each row.

Build an HTML table from an array

An array of rows maps directly onto an HTML table: the keys of the first row become the header, and each row becomes a <tr>. Run it and the Page tab shows the rendered table; change a value or add a row and run again.

The foreach (...): ... endforeach; form is the same loop written for templates, so the HTML stays readable.

Get one column from all rows

array_column() pulls one field out of every row into a flat list. Pass a third argument to key the result by another field, which turns a list of records into a lookup table.

Sort rows by a field

usort() sorts the rows with a comparison function. The spaceship operator <=> returns -1, 0 or 1, which is exactly what usort() expects. Swap $a and $b to sort in descending order.

count($players, COUNT_RECURSIVE) counts the 3 rows plus the 6 fields inside them, which is why it prints 9.

Common mistake: reading a deep key that may be missing

Reading $config['cache']['ttl'] when there is no cache key prints Warning: Undefined array key "cache", followed by Warning: Trying to access array offset on null for the next level. The ?? operator checks the whole chain at once and never warns, so it is the safe way to read optional nested values.

Frequently Asked Questions

How do I access a value in a multidimensional array in PHP?

Add one pair of brackets per level: $matrix[1][0] is row 1, column 0, and $users[0]['email'] is the email of the first user. Each bracket reads from the array returned by the one before it.

How do I loop through a multidimensional array in PHP?

Nest one foreach per level: foreach ($rows as $row) { foreach ($row as $key => $value) { ... } }. For an array of records you usually need one loop and read the fields by name: $row['name'].

How do I add an element to a multidimensional array?

Append a whole row with $rows[] = ['name' => 'Linus', 'age' => 54];, or append inside a nested array with $groups['admins'][] = 'Grace';. PHP creates the inner array if the key does not exist yet.

How do I create a 2D array filled with zeros in PHP?

Nest two array_fill() calls: $grid = array_fill(0, 3, array_fill(0, 4, 0)); gives 3 rows of 4 zeros. Each row is its own copy, so $grid[0][0] = 5; changes only the first row.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED