Associative arrays
In the previous lesson, items hung on numbered hooks. But a number says nothing about the item: is tea number 0 or 2 on a café menu? It is handier when every item has a clear name.
Picture a cloakroom that hands out name tags instead of numbered tickets. Anna's coat hangs under the tag anna, Boris's jacket under the tag boris. To get an item back, you only need to say the name.
An array in which values are found by name rather than by number is called an associative array. What a value is found by is called a key: in a list it is a number, in an associative array a name. Here is a café menu where the name of a drink serves as the key and the price as the value:
<?php
$prices = ['tea' => 120, 'coffee' => 180];
$prices['juice'] = 150;
$prices['tea'] = 100;
echo $prices['coffee'], ' ', count($prices), "\n"; // 180 3
foreach ($prices as $drink => $price) {
echo $drink, ': ', $price, "\n";
}
// tea: 100
// coffee: 180
// juice: 150Let's go through it line by line:
['tea' => 120, 'coffee' => 180]creates an array of two pairs: the key stands to the left of=>, the value to the right.$prices['juice'] = 150;adds a new pair, because the array has no key'juice'yet.$prices['tea'] = 100;finds the existing key'tea'and replaces its value.$prices['coffee']reads the value by its key and prints180, andcountcounts the pairs: there are3.foreach ($prices as $drink => $price)walks through the pairs:$drinkreceives the key,$pricea copy of the value.
The order of pairs
An array remembers the order in which pairs were added to it, and foreach walks them in exactly that order: tea, coffee, juice. Replacing a value does not change the order. The key 'tea' got a new price, 100, but stayed first.
Here the cloakroom picture parts ways with PHP. In a theater the hooks hang on the wall in one fixed order, while an array remembers the order in which the items were handed in. A new pair always goes to the end.
Remove a pair: unset
unset takes a pair off completely: the key is gone, and count drops by one.
unset($prices['coffee']);
echo count($prices), ' ', implode(' ', $prices), "\n"; // 2 100 150After unset the array holds two pairs, tea and juice, and implode glues their values: 100 150. Neither count nor implode nor foreach sees the removed pair.
Is there a key: isset and array_key_exists
A key is often checked before reading it, to avoid Warning: Undefined array key. There are two checks for this, and they answer different questions.
isset
As you already know, isset answers true if there is a value and it is not null. It works the same way with an array element: isset($prices['tea']) checks the element and gives no warning if the key is missing.
array_key_exists
array_key_exists('tea', $prices) asks one thing only: does the array have this key. What lies under it does not interest the function.
The difference shows when the key holds null:
$phones = ['anna' => '555-01', 'boris' => null];
var_dump(isset($phones['boris'])); // bool(false)
var_dump(array_key_exists('boris', $phones)); // bool(true)
var_dump(isset($phones['vera'])); // bool(false)The tag boris is there, but the hanger under it is empty. isset answers "no item", while array_key_exists answers "the tag is there". For 'vera' there is not even a tag, and both checks give false.
Interviewers like to ask how isset differs from array_key_exists. The answer:
isset($a['k'])givestrueonly if the key exists and the value under it is notnull;array_key_exists('k', $a)givestrueif the key exists, even with the valuenull.
One type for everything
A list and an associative array in PHP are not two different types but one. Every array stores key–value pairs in the order they were added. A list's keys are the numbers 0, 1, 2 that PHP handed out itself, while in an associative array you choose the keys.
That is why foreach with => works for a list too: the key is the index. And a string key can be added to a list: after $list['main'] = 'blue', the array ['red', 'green'] holds three pairs with the keys 0, 1 and 'main'.
Common mistake
A key was written without quotes:
echo $prices[tea], "\n"; // ✗Fatal error: Uncaught Error: Undefined constant "tea"Without quotes, tea is not a string but the name of a constant. The program has no such constant, and PHP stops the script at this line. A string key is always written in quotes: $prices['tea'].
Key points
- An associative array stores key–value pairs:
['tea' => 120], and a value is read by its key,$prices['tea']. - Writing to a new key adds a pair at the end, writing to an existing one changes the value in place;
unsetremoves a pair completely. foreach ($a as $k => $v)walks the pairs in the order they were added; a list is the same array with the keys0,1,2.isset($a['k'])givesfalsefor a key whose value isnulltoo, whilearray_key_existschecks only the key.