×

php · level 2 · unit 1 · lesson 1

  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

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.