Associative Arrays
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 oneThe parts:
key => valuepairs. 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
nulland 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 nullThe 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.
The shortcut
Before building an array, ask "will I look items up by position or by name?" By position → indexed list. By name → associative, with the name as the key.
The question
A visitor's basket holds
"Dune"and"Emma". What is the total?
A common mistake is quoting inside a double-quoted string wrongly. Write "Price: {$prices['Dune']}" with curly braces, which is always safe.
Drills
Answer fast — trust the rule.
What does ["Dune" => 9.99, "Dune" => 8.99] contain?
Which function lists all the titles in $prices?
$stock = ["Dune" => null]; What does isset($stock["Dune"]) return?
When should you choose an associative array over an indexed one?
Remember
- An associative array looks things up by name, not by position.
- Shortcut: "by position or by name?" decides the shape.
- Trap:
issetis false for a key whose value isnull; use array_key_exists when that matters.
