Associative arrays

Introduction

A list of numbered items is not always the right shape. A phone book looks up a person by name, a word counter looks up a word, and a record describes a person with fields such as name and age. For this you need keys that are not numbers. In PHP the same array type does both jobs: when the keys are names, the array is called an associative array. It is like a dictionary or a map in other languages, and it is the most important data structure in everyday PHP.

How it works

You write each pair as key => value:

$ages = ["Ada" => 36, "Linus" => 28];
$ages["Alan"] = 41;

The first line creates the array, and the second adds a new pair or changes an existing one. To read a value, write $ages["Ada"]. If the key does not exist, PHP gives a warning and null, so check first. The function isset($ages["Zed"]) is true when the key exists and its value is not null, and array_key_exists("Zed", $ages) checks only the key. Often the neatest choice is the ?? operator: $ages["Zed"] ?? 0 gives 0 for a missing key. To delete a pair, use unset($ages["Linus"]).

Keys can be strings or integers. PHP changes a key like "5" to the integer 5, so be careful with numeric text. The order of the pairs is the order in which you added them. A foreach loop with $key => $value visits them in that order.

Useful functions: array_keys and array_values return lists of the keys or the values, and count gives the number of pairs. To sort, use asort (by value, keep keys), arsort (by value, big to small), ksort (by key) and krsort. Plain sort would throw away the keys, so use the functions with the letter k or a for associative arrays.

A very common pattern is counting. For each item, add one to its entry:

$counts[$ch] = ($counts[$ch] ?? 0) + 1;

The ?? 0 gives the first count of a new key without a warning. The same idea builds groups: $groups[$key][] = $item; creates a list for each key.

Values can be arrays, so you can store records. [["name" => "Ada", "age" => 36], ["name" => "Alan", "age" => 41]] is a list of records, and $p["name"] reads a field of one record. This is exactly the shape of JSON data and of rows from a database.

Example

<?php
$ages = ["Ada" => 36, "Linus" => 28, "Grace" => 45];
$ages["Alan"] = 41;
echo $ages["Ada"], "\n";
echo isset($ages["Zed"]) ? "Zed found" : "Zed missing", "\n";
echo $ages["Zed"] ?? 0, "\n";
unset($ages["Linus"]);

foreach ($ages as $name => $age) {
    echo "$name is $age\n";
}
echo implode(",", array_keys($ages)), "\n";
echo implode(",", array_values($ages)), "\n";

arsort($ages);
print_r($ages);
ksort($ages);
echo implode(",", array_keys($ages)), "\n";

$counts = [];
foreach (str_split("banana") as $ch) {
    $counts[$ch] = ($counts[$ch] ?? 0) + 1;
}
foreach ($counts as $ch => $c) {
    echo "$ch=$c ";
}
echo "\n";

$people = [["name" => "Ada", "age" => 36], ["name" => "Alan", "age" => 41]];
foreach ($people as $p) {
    echo $p["name"], " ", $p["age"], "\n";
}

Line by line

  1. The array starts with three pairs, and a fourth is added.
  2. isset and ?? handle a missing key without a warning.
  3. unset removes Linus. The foreach loop prints the pairs in their original order.
  4. array_keys and array_values give the two halves of the array.
  5. arsort sorts by value from big to small, and print_r shows the result with its keys.
  6. ksort sorts by key, so the names are in alphabetical order.
  7. The counting pattern counts the letters of banana.
  8. A list of records is printed field by field.

Expected result

36
Zed missing
0
Ada is 36
Grace is 45
Alan is 41
Ada,Grace,Alan
36,45,41
Array
(
    [Grace] => 45
    [Alan] => 41
    [Ada] => 36
)
Ada,Alan,Grace
b=1 a=3 n=2 
Ada 36
Alan 41

In the real world

Configuration, JSON data from APIs, rows from a database, form fields and shopping carts are all associative arrays. Counting words, grouping orders by customer and caching results are everyday jobs that use the same patterns as this lesson. Being comfortable with them makes most PHP code easy to read.

Common mistakes

  • Reading a missing key without a check, which produces a warning.
  • Using sort on an associative array, which removes the keys.
  • Mixing up => and = when writing pairs.
  • Expecting keys "1" and 1 to be different. PHP treats them as the same key.

Best practices

  • Use ?? for safe reads and for counters.
  • Choose clear key names, always written in the same style.
  • Use asort, arsort and ksort to keep the keys.
  • Print an array with print_r to check its shape.

Summary

An associative array stores key => value pairs and keeps the order of insertion. Use isset or ?? to read keys safely, unset to remove them, and foreach with $key => $value to visit them. Sort with asort, arsort or ksort, count with ?? 0, and nest arrays to build records.

Quick check

1. How do you read a value that might be missing and use 0 if it is?
2. Which function sorts by value, big to small, and keeps the keys?
3. What does foreach ($a as $k => $v) give in $k?
4. How do you remove the pair with key "Linus"?

Key takeaways

  • An associative array stores key and value pairs and keeps their order.
  • Use isset or the null coalescing operator to read missing keys safely.
  • Sort with asort, arsort or ksort to keep the keys.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.