×

php · level 2 · unit 1 · lesson 3

  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

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.