Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 147 ยท Arrays

Associative Arrays

Use PHP associative arrays as dictionaries and records - string keys, key casting rules, isset versus array_key_exists, looping over keys and values, and counting with ??=.

In the previous lesson you saw that every PHP array is an ordered map of keys to values, and that indexed arrays simply use 0, 1, 2, โ€ฆ as keys. An associative array uses keys you choose, usually strings: 'name', 'email', 'de', 'SKU-1042'. Instead of remembering that the email lives at position 3, you write $user['email'].

Associative arrays are everywhere in PHP. $_GET and $_POST hold form fields by name, json_decode($json, true) returns them, PDO fetches database rows as them, and configuration files return them. This lesson covers creating and reading them, the rules PHP applies to keys (some of them surprising), the difference between isset() and array_key_exists(), iterating, and common patterns like lookup tables and counters.

Creating and reading

Pair each key with its value using =>. Read and write values with the key in square brackets:

PHP An associative array as a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Keys are unique. Assigning to an existing key replaces its value, and assigning to a new key adds it at the end: PHP keeps keys in insertion order, so print_r and foreach always show them in the order you added them.

When you embed a value in a double-quoted string, use braces for array access with a quoted key: "Year: {$book['year']}". The unquoted form "$book[year]" also works inside strings, but it's easy to confuse with constants, so the brace style is clearer.

Lookup tables

An associative array makes a fast dictionary: finding a value by key takes the same time whether the array has ten entries or ten million (it's a hash table inside). That makes it the natural replacement for long if/elseif chains:

PHP A lookup table instead of if-chains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The ?? operator gives a default when the key is missing, without a warning. Reading a missing key directly, $countryNames['xx'], would print Warning: Undefined array key "xx" and return null.

The key rules

A key can only be an int or a string. When you use anything else, or a string that looks like a whole number, PHP converts it. These rules explain many "where did my element go?" bugs:

You write Stored key Notes
'8' 8 (int) A string holding a canonical decimal integer becomes an int
'-5' -5 (int) Negative canonical integers too
'08', '8.0', ' 8' the string itself Not canonical, so it stays a string
true / false 1 / 0 Booleans become ints
1.7 1 Floats are truncated; deprecated since PHP 8.1 when the fraction is lost
null '' Becomes the empty string; deprecated since PHP 8.5
an array or object โ€” TypeError: Cannot access offset of type array on array
PHP How PHP converts keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The array ends up with only three entries: 8, '08' and 1. The int conversion also matters when you loop: a key written as '100' arrives in foreach as the integer 100. With declare(strict_types=1), passing that key to a function that expects a string throws a TypeError, a classic surprise when array keys are ZIP codes or numeric IDs. Cast with (string) $key when you need a string.

Never use floats, booleans or null as keys on purpose. Each is silently converted, so different values can collide (1.2 and 1.9 both become 1), and PHP now emits deprecation notices for the lossy cases.

isset versus array_key_exists

There are two ways to ask "does this key exist?", and they disagree in exactly one case: when the value is null.

  • isset($array['key']) is true if the key exists and its value is not null.
  • array_key_exists('key', $array) is true if the key exists, whatever its value.
PHP isset and array_key_exists disagree on null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Choose based on what null means in your data:

  • If null means "no value", isset() (or ??) is what you want, and it's slightly faster.
  • If a key that is present with null means something different from a missing key (for example "the user explicitly cleared their nickname" in an API update), use array_key_exists().
  • empty() is true for missing keys and for every falsy value, including 0 and '0', so it's the wrong test for a font size of zero.

Looping over keys and values

foreach ($array as $key => $value) gives you both parts of each pair, in order. When you only need one side, array_keys() and array_values() return them as plain lists:

PHP Iterating an associative array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_key_first() and array_key_last() (PHP 7.3) return the first and last key without touching the array's internal pointer. array_search() finds the key of a value; pass true as the third argument for a strict comparison, as explained in Array Functions.

Counting and grouping with ??=

A very common job is building an associative array as you go: counting words, totaling sales per customer, grouping items by category. The null-coalescing assignment ??= (PHP 7.4) makes it tidy, because it only assigns when the key is missing:

PHP Word counts and grouping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without the ??= line, the first $counts[$word]++ would read a missing key and warn. In the grouping loop, $byCustomer[$name][] = โ€ฆ creates the inner list automatically the first time a customer appears. For simple counting, array_count_values(explode(' ', $text)) does the whole job in one call.

Nested data

Values can be arrays themselves, which is how you model structured data like a JSON document or a configuration file. Read deep values by chaining keys:

PHP Nested configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

?? checks the whole chain, so $config['cache']['ttl'] ?? โ€ฆ doesn't warn even though 'cache' doesn't exist. Arrays of records, tables and deep access are the topic of Multidimensional Arrays.

Associative arrays or objects?

Arrays are perfect for quick, local, loosely structured data. Once a record shape is used across your application (a User, an Order), a class with typed properties is usually better: typos in property names become errors instead of silent new keys, editors can autocomplete, and types are checked. You'll build such classes in Classes, Properties and Methods. Until then, associative arrays are the workhorse.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many elements does ['1' => 'a', 1 => 'b', true => 'c', '01' => 'd'] have?

    '1', 1 and true all become the int key 1, so each overwrites the previous one. '01' is not a canonical integer and stays a separate string key. Result: [1 => 'c', '01' => 'd'].
  2. 2. For $a = ['x' => null], what do isset($a['x']) and array_key_exists('x', $a) return?

    isset() returns false for null values; array_key_exists() only checks that the key is present.
  3. 3. What does $prices['tea'] ?? 0 give when 'tea' is not a key of $prices?

    The ?? operator checks whether the key exists and isn't null before reading it, so a missing key just produces the default.
  4. 4. Inside foreach (['42' => 'x'] as $key => $value), what type is $key?

    The string '42' is a canonical integer, so PHP stores the key as the int 42.
  5. 5. In which order does foreach visit the keys of an associative array?

    PHP arrays are ordered maps. They remember insertion order until you sort them (see the Sorting Arrays lesson).

Summary

  • An associative array maps keys you choose to values: ['name' => 'Ada']; read with $array['name'].
  • Keys are unique and kept in insertion order; assigning to a new key adds it at the end.
  • Keys are ints or strings: canonical integer strings become ints, booleans become 0/1, floats are truncated (deprecated when lossy) and null becomes '' (deprecated in PHP 8.5).
  • isset() is false for null values; array_key_exists() only checks the key; empty() is true for any falsy value.
  • Loop with foreach ($array as $key => $value); array_keys(), array_values(), array_key_first() and array_key_last() extract parts.
  • $counts[$key] ??= 0; and $groups[$key][] = $item; are the standard patterns for counting and grouping.
  • ?? gives safe defaults, even for deep chains like $config['cache']['ttl'].

Next: Multidimensional Arrays, where you work with tables of records, grids and deeply nested data.