Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Output and Arrays  ›  Lesson

Indexed Arrays

Indexed Arrays 12 minAn indexed array stores items in order under integer keys starting at 0, so the last item's index is the count minus one.

Indexed Arrays

Pageturn's front page lists this week's featured books. You could make $book1, $book2, $book3, but then adding a fourth means renaming and rewriting. An array keeps the whole list under one name, in order, and grows when you need it to.

The rule

An indexed array numbers its items from 0, so the last one is count minus 1.

<?php
$featured = ["Dune", "Emma", "Ulysses"];

echo $featured[0];          // Dune
echo $featured[2];          // Ulysses
echo count($featured);      // 3

$featured[] = "Beloved";    // add to the end: now index 3
$featured[1] = "Persuasion"; // replace Emma

What each piece does:

  • Square brackets [...] create the array. The older array("Dune", "Emma") form still works, but the short form is standard now.
  • $featured[0] reads the first item. Indexes are integers counting up from 0.
  • count() gives the number of items, so the last index is count($featured) - 1.
  • $featured[] = ... with empty brackets appends a new item at the next index.
  • Reading a missing index such as $featured[10] gives null with an "Undefined array key" warning.

Useful helpers: in_array("Dune", $featured) tests membership, sort($featured) puts items in order (changing the array itself), and implode(", ", $featured) joins them into one string for display.

One surprise: unset($featured[1]) removes the item but does not renumber the rest. The array then has indexes 0, 2 and 3, and $featured[1] no longer exists. Call array_values($featured) to get a fresh 0, 1, 2 numbering.

The shortcut

To find an item, count from zero: the nth item lives at index n minus 1. To find the last one, use count minus 1.

Which book is third?Step 1 of 4
  1. The list

    $featured = ["Dune", "Persuasion", "Ulysses", "Beloved"];

The classic slip is reaching for $featured[count($featured)]. That index is always one past the end.

Drills

Answer fast — trust the rule.

quick drill

With $featured = ["Dune", "Emma", "Ulysses"];, what is $featured[1]?

quick drill

How do you add "Beloved" to the end of $featured?

quick drill

An array has 7 items. What is the index of the last one?

quick drill

After unset($featured[1]) on a three-item array, which indexes remain?

Remember

  • An indexed array numbers items from 0; the last is count minus 1.
  • Shortcut: position n lives at index n − 1; append with $arr[] = ....
  • Trap: unset leaves a gap in the numbering until you call array_values.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe missing index

A developer runs unset($featured[1]) on ["Dune", "Emma", "Ulysses"] and then reads $featured[1], expecting "Ulysses". Explain what they actually get and how to fix it.