Understanding PHP Associative Arrays
Learn PHP associative arrays: create them with string keys, read and update values, loop with foreach, sort by key or value, and avoid common pitfalls.
An associative array in PHP stores values under named keys instead of numeric positions. Where an indexed array answers "what's at position 2?", an associative array answers "what's the value for email?" — which is exactly how you model records, configuration, and lookups in real code.
This chapter covers how to create associative arrays, read and update them, loop over them, sort by key or value, and avoid the common mistakes that trip up beginners.
What is an associative array?
An associative array is an array whose elements are accessed by a string key (also called an index) rather than by an integer position. Each key must be unique — assigning a value to a key that already exists overwrites the old value.
$user = [
"name" => "Alice",
"email" => "[email protected]",
"age" => 30,
];Under the hood PHP has only one array type. An "indexed" array is just an associative array whose keys happen to be the integers 0, 1, 2, …. That's why you can freely mix string and integer keys in the same array.
Creating an associative array
There are two equivalent ways to build one. The short [] syntax (PHP 5.4+) is preferred in modern code; the array() function does the same thing.
// Short array syntax (recommended)
$fruits = ["apple" => "red", "banana" => "yellow", "grapes" => "green"];
// Long syntax — identical result
$fruits = array("apple" => "red", "banana" => "yellow", "grapes" => "green");You can also add keys one at a time, which is handy when building an array in a loop:
$prices = [];
$prices["coffee"] = 2.5;
$prices["tea"] = 2.0;The order in which you assign keys is preserved — PHP arrays remember insertion order, so iterating later gives you coffee before tea.
Accessing values
Read a value with its key in square brackets:
$fruits = ["apple" => "red", "banana" => "yellow"];
echo $fruits["apple"]; // redIf the key does not exist, PHP emits a warning and returns null. To read safely, check first with array_key_exists(), or use the null-coalescing operator ?? to supply a default:
$color = $fruits["mango"] ?? "unknown";
echo $color; // unknown — no warningAdding and modifying values
Assign with a key to either update an existing element or add a new one:
$fruits = ["apple" => "red"];
$fruits["apple"] = "green"; // modify existing key
$fruits["cherry"] = "dark red"; // add a new key
print_r($fruits);
// Array ( [apple] => green [cherry] => dark red )Remove an element with unset():
unset($fruits["apple"]);Looping over an associative array
A regular for loop doesn't work here because there are no sequential numeric indices. Use foreach with the key => value form to walk both keys and values:
$user = ["name" => "Alice", "email" => "[email protected]", "age" => 30];
foreach ($user as $field => $value) {
echo "$field: $value\n";
}
// name: Alice
// email: [email protected]
// age: 30Sorting associative arrays
Because keys carry meaning, you sort with functions that preserve the key/value association — sort() would throw the keys away. Use:
ksort()/krsort()— sort by key, ascending / descendingasort()/arsort()— sort by value, ascending / descending
$scores = ["Bob" => 75, "Alice" => 90, "Carol" => 82];
arsort($scores); // sort by value, highest first
foreach ($scores as $name => $score) {
echo "$name: $score\n";
}
// Alice: 90
// Carol: 82
// Bob: 75See Sorting Arrays in PHP for the full set of sort functions.
Common pitfalls
- Reusing a key overwrites silently.
["a" => 1, "a" => 2]results in["a" => 2]— no error, the first value is lost. - Numeric string keys become integers.
["10" => "x"]is stored under the integer key10.$arr["10"]and$arr[10]reach the same element. true/false/nullkeys are coerced. Atruekey becomes1,falseandnullbecome0and"". Stick to plain strings and integers as keys.- Don't rely on
for ($i = 0; …). Useforeach,array_keys(), orarray_values()to iterate when keys aren't0..n.
Conclusion
Associative arrays let you store data under meaningful, unique string keys — ideal for records, settings, and lookup tables. Read with $arr["key"] (guard missing keys with ??), update or add by assignment, remove with unset(), iterate with foreach, and sort with the key/value-preserving functions like ksort() and asort().
To go further, explore indexed arrays, multidimensional arrays (arrays of associative arrays), and array_keys() for extracting all the keys at once.