Skip to the workspace
Pebellslearn by building
Output and Arrays  ›  Lesson

Associative Arrays

Associative Arrays 13 minAn associative array stores values under named keys, so you look items up by name instead of position, and each key holds only one value.

php / Associative Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Associative Arrays

An associative array stores values under named keys, so you look items up by name instead of position, and each key holds only one value.

Read and update named fields while accounting for missing keys.

Pageturn needs a price for every book. Two parallel lists, one of titles and one of prices, fall out of step the moment someone sorts one of them. What you really want is to ask "what does Dune cost?" and get the answer directly. An associative array does exactly that.

The rule

An associative array looks things up by name, not by position.

<?php
$prices = [
    "Dune"    => 9.99,
    "Emma"    => 7.50,
    "Ulysses" => 12.00,
];

echo $prices["Dune"];          // 9.99
$prices["Beloved"] = 11.25;    // add a new key
$prices["Emma"] = 6.99;        // change an existing one
unset($prices["Ulysses"]);     // remove one

The parts:

  • key => value pairs. Keys are strings or integers; values can be anything, including other arrays.
  • Keys are unique. Writing the same key twice keeps only the last value. That is how "change a price" works.
  • Reading a missing key gives null and an "Undefined array key" warning, so check first.
  • The trailing comma after the last pair is allowed and makes adding lines tidy.

Checking whether a key exists:

isset($prices["Dune"]);              // true: exists and is not null
array_key_exists("Dune", $prices);   // true: exists, even if the value is null

The difference matters only when a value is literally null. Then isset says false while array_key_exists says true.

Handy helpers: array_keys($prices) lists the titles, array_values($prices) lists the prices, and in_array(9.99, $prices) searches the values.

In PHP, indexed and associative arrays are the same type. An indexed array is just one whose keys happen to be 0, 1, 2 and so on. A key written as the string "7" is even stored as the integer 7.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.