Associative Arrays
An associative array uses meaningful keys — usually strings — instead of numbers: a product's name, price and stock; a user's settings; a word and how often it appears. In PHP, they're not a separate type: every array is a map from keys to values, and "indexed" arrays are simply ones whose keys happen to be 0, 1, 2…
Creating and reading
Use key => value pairs:
<?php $book = [ "title" => "The Hobbit", "author" => "J. R. R. Tolkien", "year" => 1937, "inStock" => true, ]; echo $book["title"], " by ", $book["author"], "\n"; echo "Published {$book['year']}\n"; $book["price"] = 12.99; // add a new key $book["year"] = 1937; // overwrite an existing one echo count($book), " fields\n";
The Hobbit by J. R. R. Tolkien Published 1937 5 fields
The trailing comma after the last element is allowed and recommended: adding a line later then changes only one line in version control.
Keys
Keys can be integers or strings. PHP converts some key types automatically — numeric strings like "7" become integers, booleans become 0/1 — and a key can appear only once:
<?php $a = ["7" => "seven", 7 => "SEVEN", "07" => "zero-seven", true => "yes"]; var_dump($a);
array(3) {
[7]=>
string(5) "SEVEN"
["07"]=>
string(10) "zero-seven"
[1]=>
string(3) "yes"
}Arrays remember the order in which keys were inserted, and foreach always follows that order.
Looping over keys and values
<?php $prices = ["coffee" => 3.20, "tea" => 2.50, "cake" => 4.75]; foreach ($prices as $item => $price) { printf("%-7s %5.2f\n", $item, $price); } echo implode(", ", array_keys($prices)), "\n"; echo array_sum(array_values($prices)), "\n";
coffee 3.20 tea 2.50 cake 4.75 coffee, tea, cake 10.45
Checking for keys
<?php $stock = ["apples" => 12, "bananas" => 0, "cherries" => null]; var_dump(isset($stock["apples"])); var_dump(isset($stock["cherries"])); // null counts as not set var_dump(array_key_exists("cherries", $stock)); // the key itself exists echo $stock["pears"] ?? 0, "\n";
bool(true) bool(false) bool(true) 0
isset is faster and usually what you want; array_key_exists distinguishes "missing" from "present but null".
Counting with an associative array
Using values as keys is the classic way to count occurrences or group things:
<?php $text = "the cat sat on the mat the end"; $counts = []; foreach (explode(" ", $text) as $word) { $counts[$word] = ($counts[$word] ?? 0) + 1; } arsort($counts); // sort by value, highest first, keeping keys foreach ($counts as $word => $n) { echo str_pad($word, 4), str_repeat("#", $n), " $n\n"; } print_r(array_count_values(["a", "b", "a", "c", "a"]));
the ### 3
cat # 1
sat # 1
on # 1
mat # 1
end # 1
Array
(
[a] => 3
[b] => 1
[c] => 1
)array_count_values does the counting in one call. Sorting functions like arsort are covered in lesson 24.
Grouping
<?php $people = [ ["name" => "Amir", "city" => "Leeds"], ["name" => "Bea", "city" => "York"], ["name" => "Cleo", "city" => "Leeds"], ]; $byCity = []; foreach ($people as $person) { $byCity[$person["city"]][] = $person["name"]; } foreach ($byCity as $city => $names) { echo "$city: ", implode(", ", $names), "\n"; }
Leeds: Amir, Cleo York: Bea
$byCity[$city][] = … creates the inner array automatically the first time a city appears.
Arrays as records
Associative arrays are often used as simple records — rows from a database or decoded JSON usually arrive this way. For data with a fixed shape that you pass around a lot, a class with typed properties (lesson 33) gives you autocompletion and error checking; arrays are best for quick, local or truly dynamic data.
Combining associative arrays
With string keys, array_merge and the + operator behave differently: array_merge lets later values win, while + keeps the first value for each key — handy for applying defaults:
<?php $defaults = ["theme" => "light", "fontSize" => 14, "lang" => "en"]; $user = ["theme" => "dark", "fontSize" => 16]; print_r(array_merge($defaults, $user)); print_r($user + $defaults); print_r(array_flip(["red" => 1, "green" => 2]));
Array
(
[theme] => dark
[fontSize] => 16
[lang] => en
)
Array
(
[theme] => dark
[fontSize] => 16
[lang] => en
)
Array
(
[1] => red
[2] => green
)Careful: with numeric keys, array_merge appends and renumbers, while + keeps the left-hand values for duplicate indexes.
Try it yourself
Scan items at a shop till: count the quantities and price them from a price list, skipping unknown items.
apple x3 1.20 milk x1 1.15 bread x1 2.10 cheese x1 (no price) Total: 4.45