php · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Give every value in an array a of its own.
In Level 1, every item sat at a number: 0, 1, 2. That suits a queue, but not facts about one thing. Is the pet's name at 0 or at 2? An labels each value with a key, like the labels on a filing cabinet.
Write each key, then =>, then its value: ["name" => "Biscuit", "age" => 4]. Read => as points to. To get a value back, put its key in square brackets: $pet["name"].
Put a value at a key to change it, or at a new key to add one. Ask for a key that is not there and PHP stops with Undefined array key, the same as a missing index.
<?php
$pet = ["name" => "Biscuit", "type" => "cat", "age" => 4];
echo $pet["name"] . " is a " . $pet["type"] . "\n";
$pet["age"] = 5;
$pet["food"] = "fish";
echo "{$pet["name"]} is now {$pet["age"]} and eats {$pet["food"]}\n";
echo count($pet) . " facts\n"; Inside double quotes, wrap a key lookup in curly brackets, like {$pet["name"]}, so PHP can see where it ends.
guess first
Leo scores again and Ava joins. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$scores = ["Mia" => 12, "Leo" => 9];
$scores["Leo"] = 15;
$scores["Ava"] = 7;
echo $scores["Leo"] + $scores["Ava"] . "\n";
your turn
Your turn. Describe a film you love.
Type a film's title and the year it came out. Then give it a rating out of 5 and run it.
fix it
The café order crashes. Can you fix it?
- Read the error:
Undefined array key. Which key is PHP looking for? - Compare the keys on line 2 with the keys used on line 3, letter by letter.
- The key is
"drink", with no s. Change"drinks"to"drink", then press run.
nailed it
your arrays have labels now. :D
- An associative array finds each value by its key.
- Write
"key" => value, then read it with$array["key"]. - A key that is not there stops PHP with an error.
new words in your collection
- key
- associative array
This lesson isn’t saved. A free account remembers every lesson you finish.