01 · THE IDEAREAD → TRY → LEARN
Arrays that use names instead of positions
A list such as ["red", "green"] finds its values by position. Often a name describes the data better. A user has a name, a role and a number of visits. An associative array stores each value under a key you choose, so you can ask for $user["role"] instead of remembering that the role sits at position 1.
PHP does not have a separate type for this. Every array is an ordered map that links keys to values. The same array can hold integer keys and string keys, and the order in which you added elements is preserved.
Creating, reading and changing
Write each pair as key => value. Read a value with square brackets and the key. Assign to a key that does not exist yet and PHP adds it. Assign to an existing key and PHP replaces the old value.
$user = [
"name" => "Ada",
"role" => "admin",
"visits" => 3,
];
echo $user["name"], PHP_EOL;
$user["visits"] = $user["visits"] + 1;
$user["city"] = "London";
echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;Ada
{"name":"Ada","role":"admin","visits":4,"city":"London"}
The new city key appears at the end, and visits keeps its original place even though its value changed. To remove a pair, call unset($user["role"]). Other keys are not renumbered or moved.
Missing keys
Reading a key that is not in the array does not stop the script. PHP issues a warning and the result is null. Warnings in the middle of your output are rarely what you want, so check first or provide a fallback.
The null coalescing operator ?? does both in one expression. It returns the left side if that side exists and is not null. Otherwise it returns the right side. It never raises a warning for a missing key.
There is one subtle point. A key can exist and still hold null. For ??, that counts as "no value", just like isset(). When you need to know whether the key is present at all, use array_key_exists().
$settings = [
"theme" => "dark",
"sidebar" => null,
];
echo $settings["theme"] ?? "light", PHP_EOL;
echo $settings["language"] ?? "en", PHP_EOL;
echo $settings["sidebar"] ?? "hidden", PHP_EOL;
var_dump(array_key_exists("sidebar", $settings));
var_dump(isset($settings["sidebar"]));dark en hidden bool(true) bool(false)
The sidebar key exists, so array_key_exists() reports true. Its value is null, so isset() reports false and ?? chooses the fallback.
You can also chain the operator: $a["x"] ?? $a["y"] ?? "none" tries each option from left to right and returns the first one that is not null.
Keys are not always what they look like
Keys can only be integers or strings, so PHP converts other values before storing them:
- A string holding a plain decimal integer, such as
"8", becomes the integer8. - A string such as
"08"is not a plain integer, so it stays a string. - Booleans become integers:
trueis1andfalseis0. nullbecomes the empty string"", but usingnullas a key is deprecated as of PHP 8.5. Write""when you mean an empty key.- Arrays and objects cannot be keys.
If two keys convert to the same final key, the later value silently overwrites the earlier one.
$map = [
"8" => "a",
"08" => "b",
true => "c",
];
echo json_encode(array_keys($map)), PHP_EOL;[8,"08",1]
The first key is stored as the integer 8, which is why it prints without quotes. The second keeps its leading zero and stays a string.
Common mistakes
- Writing
$user[name]without quotes. That treatsnameas a constant name instead of the string"name". Always quote string keys. - Using
||or?:where??is needed.?:also replaces0,""and"0", which may be perfectly valid values. - Assuming a key is absent because its value is
null. Usearray_key_exists()when presence matters. - Expecting
unset()to shift later elements. It removes only that one pair.
Your turn
Write getDisplayName(array $user): string. It should return the nickname value if that key exists and is not null. Otherwise it should return the name value. If neither is available, it returns "Guest". An empty-string nickname is a real value, so it must be returned unchanged. Chaining ?? is all you need.
Recap
An associative array is a normal PHP array with meaningful keys. Quote string keys, remember that integer-like strings and booleans are converted (and null keys are deprecated), and use ?? to supply fallbacks without warnings.
Arrays
- Create and read string-keyed arrays
- Handle missing keys with null coalescing