Multi-dimensional Arrays
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"]:
$catalog[1]is the second row: the whole Emma array.["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.
The shortcut
Read a lookup from left to right, one bracket at a time, and say what you are holding after each step.
Start with the whole thing
$catalogis a list of three books.
The usual mistake is reversing the order, as in $catalog["stock"][1]. The outer array has no "stock" key: the list comes first, then the field.
Drills
Answer fast — trust the rule.
What is $catalog[0]["price"] before any changes?
How many items does count($catalog) report for the three-book catalogue?
Which expression gives Ulysses's stock?
Which call returns ["Dune", "Emma", "Ulysses"] from the catalogue?
After $catalog[0]["stock"]--;, what is Dune's stock?
Remember
- An array can hold arrays; each pair of brackets goes one level deeper.
- Shortcut: read lookups left to right, naming what you hold after each bracket.
- Trap: the list index comes before the field name, and count counts only the outer level.
