php · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Check that a key is there before you use it.
Reading a missing key stops your program, so check first. gives true when the key exists and holds something other than null. Otherwise it gives false, and nothing crashes.
Often you want a fallback: use this key's value, or else this one. The , ??, does that in one go. $stock["pears"] ?? 0 gives the pears if they are there, and 0 if not.
To take a key and its value out of an array, use . Afterwards the array has one pair fewer.
<?php
$stock = ["apples" => 3, "plums" => 5];
if (isset($stock["apples"])) {
echo "Apples: {$stock["apples"]}\n";
}
$pears = $stock["pears"] ?? 0;
echo "Pears: $pears\n";
unset($stock["plums"]);
echo count($stock) . " fruit left on the list\n"; You will lean on ?? a lot later, because a visitor can leave any part of a form empty.
guess first
Some settings are missing. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$settings = ["theme" => "dark", "sound" => null];
$theme = $settings["theme"] ?? "light";
$sound = $settings["sound"] ?? "on";
$size = $settings["size"] ?? "medium";
echo "$theme, $sound, $size\n";
your turn
Your turn. Look up an age.
Type a name in the blank. Try Mia first, then run it again with a name that is not in the array.
fix it
The first vote for fish crashes. Can you fix it?
- Line 3 reads
$votes["fish"]before anyone has voted for fish. Is that key there yet? - Use
??so a missing count falls back to 0. Put brackets round it, so the fallback happens before the+ 1. - Change line 3 to
$votes["fish"] = ($votes["fish"] ?? 0) + 1;, then press run.
nailed it
missing keys cannot trip you up now. :D
issetchecks that a key is there and notnull.??gives a fallback when a value is missing.unsettakes a key and its value out.
new words in your collection
- isset
- null coalescing operator
- unset
This lesson isn’t saved. A free account remembers every lesson you finish.