Multidimensional Arrays

An array can contain other arrays, forming a grid or table of data.

Syntax$grid[$row][$column]

A multidimensional array is an array whose elements are themselves arrays. This is useful for representing tables, matrices or records.

Access nested values with multiple sets of square brackets.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Represent a shopping cart as a 2-D array where each row holds a product's id, name, quantity, and price.
  • Store a week's worth of hourly temperature readings as a nested array indexed by day and hour.
  • Model a CSV import as a multidimensional array before iterating over rows and columns.

More examples

2-D array access

Chaining two bracket lookups accesses a specific column inside a specific row of a 2-D array.

Example · php
<?php
$cart = [
    ['id' => 1, 'name' => 'Widget', 'qty' => 2, 'price' => 9.99],
    ['id' => 2, 'name' => 'Gadget', 'qty' => 1, 'price' => 24.99],
];

echo $cart[0]['name'];  // Widget
echo $cart[1]['price']; // 24.99

Nested foreach loops

Nested foreach loops traverse each row then each cell, the natural pattern for grid or table data.

Example · php
<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

foreach ($matrix as $row) {
    foreach ($row as $cell) {
        echo str_pad($cell, 3);
    }
    echo "\n";
}

Array of associative arrays

An array of associative arrays is the common shape for database result sets; array_filter() picks matching rows.

Example · php
<?php
$users = [
    ['name' => 'Alice', 'role' => 'admin'],
    ['name' => 'Bob',   'role' => 'editor'],
    ['name' => 'Carol', 'role' => 'viewer'],
];

$admins = array_filter($users, fn($u) => $u['role'] === 'admin');
echo $admins[0]['name']; // Alice

Discussion

  • Be the first to comment on this lesson.