AnyCompiler

Associative Arrays

This is the single most important structural fact about PHP: there is no separate "list type" and "dictionary type". [10, 20, 30] and ["name" => "Grace", "age" => 85] are the exact same underlying array type — PHP calls both of them just array. An indexed array is really an associative array whose keys happen to be the auto-incrementing integers 0, 1, 2, ...; write your own keys with => instead, and the same type becomes a dictionary. Keys can be strings or integers, in any mix, and lookup, assignment, and iteration all work identically either way.

<?php
$user = ["name" => "Grace", "age" => 85, "lang" => "COBOL"];
echo $user["name"], "\n";
$user["age"] = 86;
$user["active"] = true;
print_r($user);
foreach ($user as $key => $value) {
    echo "$key => " . (is_bool($value) ? ($value ? "true" : "false") : $value) . "\n";
}
var_dump(array_key_exists("name", $user));
Output
Grace
Array
(
    [name] => Grace
    [age] => 86
    [lang] => COBOL
    [active] => 1
)
name => Grace
age => 86
lang => COBOL
active => true
bool(true)

$user["age"] = 86 updates an existing key in place; $user["active"] = true adds a brand-new one — the same square-bracket syntax does both. Notice print_r() showed [active] => 1 for a value that's actually the boolean true: print_r() and echo both render true as 1 and false as an empty string, which is why the foreach loop above converts it explicitly with is_bool() before printing — a real, easy-to-miss PHP quirk worth knowing about up front. array_key_exists() checks for a key regardless of its value (unlike isset(), which also returns false for a key whose value is literally null). Next: control flow — if/elseif/else and switch.

Practice exercise

Create $person = ["name" => "Grace", "role" => "Admiral"], then foreach over it printing "$key: $value" on each line.