Associative Arrays
PHP doesn't have a separate dictionary or map type — an array with string keys instead of numeric ones is the associative array, using the exact same square-bracket syntax you already know.
Creating one
<?php
$person = [
"name" => "Jamie",
"age" => 34,
"city" => "Austin"
];
echo $person["name"] . "\n";
echo $person["age"] . "\n";
?>
Jamie 34
=> pairs a key with its value. Every array in PHP, whether it looks "indexed" or "associative," is really the same ordered map type internally — an indexed array is just one whose keys happen to be sequential integers starting at 0.
Adding, updating, and checking keys
<?php $person = ["name" => "Jamie", "age" => 34]; $person["email"] = "jamie@example.com"; $person["age"] = 35; var_dump(isset($person["email"])); var_dump(isset($person["phone"])); var_dump(array_key_exists("age", $person)); print_r($person); ?>
bool(true)
bool(false)
bool(true)
Array
(
[name] => Jamie
[age] => 35
[email] => jamie@example.com
)
Assigning to an existing key overwrites its value; assigning to a new key adds it, appended at the end. isset() is the standard way to check whether a key exists without triggering a warning for a missing one — reading $person["phone"] directly when it isn't set would produce a warning rather than a clean false.
Looping with key and value together
The two-variable form of foreach gives you both the key and the value on each pass — this is how you'll iterate over associative arrays almost every time:
<?php $prices = ["coffee" => 4.5, "tea" => 3.0, "juice" => 5.25]; foreach ($prices as $item => $price) { echo ucfirst($item) . ": \$" . $price . "\n"; } ?>
Coffee: $4.5 Tea: $3 Juice: $5.25
foreach ($prices as $item => $price) destructures each pair as it goes. ucfirst() capitalizes just the first letter of a string, handy for turning a lowercase key into something presentable.
foreach — the order you add keys in is the order you'll get them back, which makes them genuinely useful as lightweight ordered records, not just lookup tables.