php · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three players and their goals. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$team = [
["name" => "Ava", "goals" => 3],
["name" => "Ben", "goals" => 5],
["name" => "Cal", "goals" => 1],
];
echo $team[1]["name"] . " scored " . $team[1]["goals"] . "\n";
echo "Team goals: " . array_sum(array_column($team, "goals")) . "\n";
your turn
Your turn. Add a pet to the register.
Type a name and a kind of animal for the new record. Run it and see your pet join the list.
fix it
This should show the first film. Can you fix it?
- Read the error:
Undefined array key "title". The outer array only has keys 0 and 1. - Reach in from the outside: first pick the record, then the key inside it.
- Swap the brackets so it reads
$films[0]["title"], then press run.
nailed it
you packed a whole table into one array. :D
- A nested array holds arrays, often a list of records.
$list[1]["title"]picks the record first, then the key.array_columncollects one key from every record.
new words in your collection
- nested array
- record
- array_column
This lesson isn’t saved. A free account remembers every lesson you finish.