Associative arrays

The array of the last lesson was a list with numeric positions. Give the keys names and the same structure of PHP becomes a map, which is how a record, a settings table or a row of data is held.

Keys and values

An associative array maps string keys to values, like a small dictionary: each name points to exactly one value. The => arrow pairs a key with its value when the array is built.

<?php $user = ["name" => "Ada", "age" => 36]; echo $user["name"], PHP_EOL;

php keys.php

Ada

The key is the word in quotes, not a position, so "name" keeps its meaning whatever the order of the pairs. The same key written twice would keep only the last value.

Iterate with key and value

The two-variable foreach form hands you both halves of every pair: the key on the left, the value on the right. It is the standard way to print settings, render option lists, and transform maps.

<?php $user = ["name" => "Ada", "age" => 36]; foreach ($user as $key => $value) { echo $key . ": " . $value, PHP_EOL; }

php iterate.php

name: Ada
age: 36

The pairs come out in the order they were written, and the dot glues each key to its value with a colon and a space that the array itself does not hold.

isset, empty and array_key_exists

Three checks answer three different questions. isset is false for missing keys and for keys holding null. array_key_exists() cares only about the key itself, so it stays true even when the value is null. empty treats missing, null, empty string, zero, and empty array all as empty.

<?php $data = ["a" => null]; var_dump(isset($data["a"])); var_dump(array_key_exists("a", $data)); var_dump(empty($data["b"]));

php check.php

bool(false)
bool(true)
bool(true)

The key "a" exists with a null value: isset says false and array_key_exists says true. The key "b" does not exist at all, and empty reads that as empty.

Sort by value and key

Plain sort() reorders values and renumbers keys, which destroys a map. Use asort() to order by value while keeping keys attached, and ksort() to order by key.

<?php $scores = ["bob" => 12, "ada" => 30, "cid" => 7]; asort($scores); foreach ($scores as $name => $score) { echo $name . ": " . $score, PHP_EOL; } echo "--" . PHP_EOL; ksort($scores); foreach ($scores as $name => $score) { echo $name . ": " . $score, PHP_EOL; }

php sort.php

cid: 7
bob: 12
ada: 30
--
ada: 30
bob: 12
cid: 7

The first three lines follow the score, so the names stay with their numbers. The last three follow the name, and the scores travel with them; a plain sort would have thrown the names away and left 7, 12 and 30 at the positions 0, 1 and 2.

Exercises

  1. Add a "city" key to the user and print it. What happens when the key is missing, and which function would you use to check first?
  2. Print the iterate.php map in reverse order with array_reverse.
  3. Add a key with the value 0 to check.php and test it with all three checks. Which of them call it empty?
  4. Sort the scores by value in descending order with arsort, then print the names.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What pairs a key with its value in an array literal?

    Answer

    The => arrow

    The double arrow writes one pair, as in "name" => "Ada"; the comma separates the pairs.

  2. Which check is false for an existing key whose value is null?

    Answer

    isset()

    isset tests the value too, and null fails it; array_key_exists tests only the key.

  3. Which function sorts a map by value and keeps its keys?

    Answer

    asort()

    asort orders by value and preserves the keys; sort renumbers them, and ksort orders by key.

  4. What happens to the keys when plain sort() runs on an associative array?

    Answer

    They are thrown away and the values are renumbered

    sort works on list positions: it keeps the values, drops their string keys and gives them the numbers 0, 1, 2.

  5. What does this program print? <?php $user = ["name" => "Ada", "age" => 36]; echo $user["age"];

    Answer

    36

    The key "age" points to the integer 36, which echo prints.

  6. What does this program print? <?php $user = ["name" => "Ada", "age" => 36]; foreach ($user as $key => $value) { echo $key; }

    Answer

    nameage

    The loop echoes only the keys, one after the other, so they run together as nameage.

  7. What does this program print? <?php $data = ["a" => null]; var_dump(isset($data["a"]));

    Answer

    bool(false)

    isset is false when the value is null, even though the key exists.

  8. What does this program print? <?php $data = ["a" => null]; var_dump(array_key_exists("a", $data));

    Answer

    bool(true)

    The key "a" is in the array, and array_key_exists does not look at the value.

  9. What does this program print? <?php $scores = ["bob" => 12, "ada" => 30]; asort($scores); foreach ($scores as $name => $score) { echo $name; }

    Answer

    bobada

    asort orders by value, so bob with 12 comes before ada with 30, and only the names print.

  10. What does this program print? <?php $scores = ["bob" => 12, "ada" => 30]; sort($scores); echo $scores[0];

    Answer

    12

    sort renumbers the values, so position 0 holds the smallest number, 12, and the names are gone.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev