php · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item in an array has an , starting at 0.
Every item has a place number called its index. PHP counts from 0, so the first item is $queue[0] and the second is $queue[1]. Picture a queue where the person at the front is number 0.
Put a new value at an index to replace that item: $queue[1] = "Bea";. Empty square brackets add a new item on the end: $queue[] = "Dan";.
Ask for an index with no item and PHP stops with Undefined array key. The last item is always at count($queue) - 1.
<?php
$queue = ["Ava", "Ben", "Cleo"];
echo $queue[0] . " is first\n";
$queue[1] = "Bea";
$queue[] = "Dan";
echo implode(", ", $queue) . "\n"; The index always goes in square brackets, straight after the array's name.
guess first
A rabbit joins the pets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$pets = ["cat", "dog", "fish"];
$pets[] = "rabbit";
echo $pets[1] . " and " . $pets[3] . "\n";
your turn
Your turn. Change the team.
Swap one player for someone new: type an index from 0 to 2, then a name. Type another name to add on the end, then run it.
fix it
This should show the last cake, lemon. Can you fix it?
- Read the error:
Undefined array key 3. How many cakes are there, and where does counting start? - Counting from 0, the three cakes sit at index 0, 1 and 2.
- Change the 3 to 2 inside the square brackets, then press run.
nailed it
you can find and change any item. :D
- Indexes start at 0, so the first item is
[0]. $list[1] = ...replaces an item.$list[] = ...adds one.- The last item is at
count($list) - 1.
new words in your collection
- index
This lesson isn’t saved. A free account remembers every lesson you finish.