×

php · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Pack arrays inside an array to store a whole table.

An array can hold other arrays. That is a . A common shape is a list of records: each is an associative array of facts about one thing, like one book on a shelf.

Use two sets of square brackets to reach inside. $books[1]["title"] means: take record 1, then its title. Loop over the list with foreach and each go hands you one whole record.

collects the value at one key from every record, so you get a plain list of titles.

<?php
$books = [
    ["title" => "Matilda", "pages" => 240],
    ["title" => "Holes", "pages" => 272],
    ["title" => "Wonder", "pages" => 316],
];
echo $books[1]["title"] . "\n";
foreach ($books as $book) {
    echo "{$book["title"]}: {$book["pages"]} pages\n";
}
echo implode(", ", array_column($books, "title")) . "\n";

Spreading a big array over several lines, one record per line, keeps it readable, and a comma after the last record is fine.