Associative Arrays
What Is an Associative Array?
In simple terms: An associative array stores values under names (keys) instead of position numbers. Instead of "the second item", you ask for "the email" or "the price". Technically: An associative array is a PHP array whose keys are meaningful strings (or chosen integers) rather than automatic sequential indexes. It works like a dictionary or map: each key is unique and points to one value. Lookups by key are very fast, regardless of the array's size.
$user = [
'name' => 'Asha',
'email' => 'asha@example.com',
'city' => 'Chennai',
];
Why Associative Arrays Are So Common
- Records: a user, product, or order has named fields.
- Settings: configuration options by name.
- Lookups: country codes to names, status codes to labels.
- Counting and grouping: words to counts, categories to products.
- Data from outside: database rows (
fetch(PDO::FETCH_ASSOC)), form data ($_POST), and decoded JSON objects all arrive as associative arrays.
Creating Associative Arrays
Syntax
$array = [
'key1' => value1,
'key2' => value2,
];
The => operator ("double arrow") assigns a value to a key.
Example
<?php
$product = [
'sku' => 'LAMP-01',
'name' => 'Desk Lamp',
'price' => 1299,
'inStock' => true,
];
print_r($product);
Output
Array
(
[sku] => LAMP-01
[name] => Desk Lamp
[price] => 1299
[inStock] => 1
)
print_r() shows true as 1; use var_dump() when you need to see exact types.
Accessing Values
<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com', 'city' => 'Chennai'];
echo $user['name'] . "\n";
echo "Lives in {$user['city']}\n";
Output
Asha
Lives in Chennai
In double-quoted strings, use curly braces ({$user['city']}) to access elements with quoted keys (see String Interpolation).
Missing Keys
<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com'];
echo $user['phone'];
Output
PHP Warning: Undefined array key "phone" in /path/script.php on line 4
Reading a key that does not exist raises a warning and returns null. Optional keys should be read safely:
<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com'];
echo $user['phone'] ?? 'Phone not provided';
echo "\n";
Output
Phone not provided
isset() vs array_key_exists()
<?php
$profile = ['name' => 'Asha', 'nickname' => null];
var_dump(isset($profile['nickname']));
var_dump(array_key_exists('nickname', $profile));
var_dump(isset($profile['age']));
Output
bool(false)
bool(true)
bool(false)
isset()returnsfalsefor keys whose value isnull.array_key_exists()returnstruewhenever the key exists, even if its value isnull. Usearray_key_exists()when "set to null" and "not set at all" mean different things (for example, a user who explicitly cleared their nickname).
Adding, Updating, and Removing
<?php
$settings = ['theme' => 'light', 'language' => 'en'];
$settings['perPage'] = 25; // add a new key
$settings['theme'] = 'dark'; // update an existing key
unset($settings['language']); // remove a key
print_r($settings);
Output
Array
(
[theme] => dark
[perPage] => 25
)
Assigning to a key either creates it (if it does not exist) or replaces its value (if it does). Keys are unique — an array cannot contain the same key twice.
Looping Over Associative Arrays
<?php
$stock = ['Keyboard' => 12, 'Mouse' => 0, 'Monitor' => 4];
foreach ($stock as $product => $quantity) {
$status = $quantity > 0 ? "$quantity available" : 'sold out';
echo "$product: $status\n";
}
echo "Products: " . implode(', ', array_keys($stock)) . "\n";
echo "Total units: " . array_sum($stock) . "\n";
Output
Keyboard: 12 available
Mouse: sold out
Monitor: 4 available
Products: Keyboard, Mouse, Monitor
Total units: 16
foreach ($array as $key => $value)gives both the key and the value.array_keys()returns the keys as a list;array_values()returns the values as a list.- Functions like
array_sum()work on the values.
Key Rules
Insertion Order Is Preserved
Elements stay in the order they were added. Sorting functions change the order explicitly (see below).
Keys Are Case-Sensitive
<?php
$data = ['Name' => 'Asha', 'name' => 'Bala'];
echo count($data) . "\n";
echo $data['name'] . "\n";
Output
2
Bala
'Name' and 'name' are different keys. Normalize keys (for example, to lowercase) when they come from user input or external systems.
Integer-Like String Keys Become Integers
A string key that looks like a canonical integer, such as "42", is stored as the integer 42. "042" and "4.2" stay strings. This rarely matters, but explains why $array["42"] and $array[42] refer to the same element (see PHP Type Juggling).
Sorting Associative Arrays
Sorting functions for associative arrays keep each key with its value:
| Function | Sorts By | Order |
|---|---|---|
asort() | Value | Ascending |
arsort() | Value | Descending |
ksort() | Key | Ascending |
krsort() | Key | Descending |
<?php
$prices = ['Mouse' => 799, 'Keyboard' => 1499, 'Cable' => 199];
asort($prices);
print_r($prices);
ksort($prices);
print_r($prices);
Output
Array
(
[Cable] => 199
[Mouse] => 799
[Keyboard] => 1499
)
Array
(
[Cable] => 199
[Keyboard] => 1499
[Mouse] => 799
)
sort() and rsort() would discard the keys and re-index the array from 0 — a common mistake with associative arrays. Sorting is covered in Sorting Arrays.
Associative Arrays as Lookup Tables
Because looking up a key is very fast, associative arrays are ideal for mapping codes to values:
<?php
$statusLabels = [
'pending' => 'Awaiting payment',
'paid' => 'Payment received',
'shipped' => 'On the way',
'delivered' => 'Delivered',
];
$orders = [['id' => 1, 'status' => 'shipped'], ['id' => 2, 'status' => 'refunded']];
foreach ($orders as $order) {
$label = $statusLabels[$order['status']] ?? 'Unknown status';
echo "Order {$order['id']}: $label\n";
}
Output
Order 1: On the way
Order 2: Unknown status
One array lookup replaces a chain of if statements, and ?? handles unknown codes.
Counting With an Associative Array
<?php
$votes = ['PHP', 'Python', 'PHP', 'Go', 'PHP', 'Python'];
$counts = [];
foreach ($votes as $language) {
$counts[$language] = ($counts[$language] ?? 0) + 1;
}
arsort($counts);
print_r($counts);
Output
Array
(
[PHP] => 3
[Python] => 2
[Go] => 1
)
Each language becomes a key the first time it appears (?? 0 supplies the starting count). PHP's array_count_values($votes) performs the same counting in one call.
Combining Defaults With Overrides
A common task is applying user settings on top of default settings:
<?php
$defaults = ['theme' => 'light', 'language' => 'en', 'perPage' => 20];
$userSettings = ['language' => 'ta', 'perPage' => 50];
print_r(array_replace($defaults, $userSettings));
print_r($userSettings + $defaults);
Output
Array
(
[theme] => light
[language] => ta
[perPage] => 50
)
Array
(
[language] => ta
[perPage] => 50
[theme] => light
)
array_replace($defaults, $overrides)keeps the order of the defaults and replaces values with matching keys.$overrides + $defaults(the union operator) keeps the left array's values and adds missing keys from the right. Both produce the same settings; they differ only in key order.array_merge()behaves likearray_replace()for string keys. See Merge Arrays.
Associative Arrays and JSON
JSON objects map directly to associative arrays:
<?php
$json = '{"id": 42, "name": "Asha", "address": {"city": "Madurai", "pin": "625001"}}';
$customer = json_decode($json, true);
echo $customer['name'] . ' — ' . $customer['address']['city'] . "\n";
$customer['verified'] = true;
echo json_encode($customer) . "\n";
Output
Asha — Madurai
{"id":42,"name":"Asha","address":{"city":"Madurai","pin":"625001"},"verified":true}
json_decode() with true produces nested associative arrays, which can be read and modified like any other array and encoded back to JSON.
Practical Example: Turning Parallel Lists Into a Record
<?php
$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
$sales = [12500, 9800, 15200, 11000, 18750];
$salesByDay = array_combine($days, $sales);
arsort($salesByDay);
$bestDay = array_key_first($salesByDay);
echo "Best day: $bestDay (₹" . number_format($salesByDay[$bestDay]) . ")\n";
echo "Weekly total: ₹" . number_format(array_sum($salesByDay)) . "\n";
foreach ($salesByDay as $day => $amount) {
printf("%-3s %s\n", $day, str_repeat('█', intdiv($amount, 2500)));
}
Output
Best day: Fri (₹18,750)
Weekly total: ₹67,250
Fri ███████
Wed ██████
Mon █████
Thu ████
Tue ███
Step-by-Step Explanation
array_combine($days, $sales)builds an associative array using the first array as keys and the second as values. Each day and its sales amount now stay together.arsort()sorts by sales, highest first, keeping the day names.array_key_first()returns the first key after sorting — the best day.- A simple text bar chart uses one block per ₹2,500 (
intdiv($amount, 2500)). With two separate lists, sorting the sales would have broken the link to the days. The associative array keeps the data consistent.
Common Mistakes
Reading Optional Keys Without a Default
Effect: "Undefined array key" warnings. Fix: Use ??, isset(), or array_key_exists().
Using sort() on Associative Arrays
Effect: Keys are lost and replaced with 0, 1, 2, …. Fix: Use asort(), arsort(), ksort(), or krsort().
Inconsistent Key Case or Spelling
Effect: 'Email' and 'email' become two different entries. Fix: Normalize keys and define them in one place (constants or a class).
Treating isset() as "Key Exists"
Effect: Keys with null values are reported as missing. Fix: Use array_key_exists() when the difference matters.
Large "Magic" Arrays Passed Everywhere
Effect: Typos in keys are not caught, and nobody knows which keys an array should contain. Fix: For important domain data, use classes with typed properties; keep associative arrays for simple data and lookups.
Best Practices
- Use associative arrays for records, settings, lookups, and counting.
- Read optional keys with
??and chooseisset()orarray_key_exists()deliberately. - Use key-preserving sort functions (
asort,arsort,ksort,krsort). - Combine related lists with
array_combine()instead of keeping parallel arrays. - Keep key names consistent, and consider classes for complex, frequently used structures. Official reference: https://www.php.net/manual/en/language.types.array.php