Skip to the workspace
Pebellslearn by building
Output and Arrays  ›  Capstone Project

Multi-dimensional Arrays

Multi-dimensional Arrays 15 minA multi-dimensional array holds arrays inside an array, and each pair of brackets in a lookup goes one level deeper, usually list index first and field name second.

php / Multi-dimensional Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Multi-dimensional Arrays

A multi-dimensional array holds arrays inside an array, and each pair of brackets in a lookup goes one level deeper, usually list index first and field name second.

Navigate nested records and keep each level's key or index visible.

Pageturn's catalogue needs more than a price per title: each book has a title, a price and a stock count. A single flat array cannot hold that neatly, but an array of arrays can. This is how most real PHP data looks, including rows from a database and decoded JSON.

The rule

An array can hold arrays — one pair of brackets per level.

<?php
$catalog = [
    ["title" => "Dune",    "price" => 9.99,  "stock" => 3],
    ["title" => "Emma",    "price" => 7.50,  "stock" => 0],
    ["title" => "Ulysses", "price" => 12.00, "stock" => 5],
];

echo $catalog[1]["title"];     // Emma
echo $catalog[2]["price"];     // 12
$catalog[0]["stock"]--;         // Dune now has 2
$catalog[] = ["title" => "Beloved", "price" => 11.25, "stock" => 4];

Reading $catalog[1]["title"]:

  1. $catalog[1] is the second row: the whole Emma array.
  2. ["title"] then picks one field from that row.

Each pair of brackets steps one level deeper. The outer array here is indexed (a list of books); each inner one is associative (named fields). This "list of records" shape is the most common one you will meet.

Two useful tools:

  • count($catalog) counts the rows (3 before the append), not every value inside them.
  • array_column($catalog, "title") pulls one field from every row: ["Dune", "Emma", "Ulysses"].

Inside double quotes, wrap deep lookups in braces: "Now: {$catalog[0]['title']}".

Use print_r($catalog) to see the whole structure indented, level by level.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.