A PHP associative array is an array whose elements are accessed by named keys, usually strings, instead of by position. You write it as ['name' => 'Asha', 'age' => 30] and read a value with $person['name']. It is PHP's version of a dictionary or hash map, and it keeps the order in which you inserted the elements.
In PHP there is only one array type. An indexed array and an associative array are the same structure; the difference is whether the keys are automatic integers or keys you choose.
Use key => value pairs inside square brackets.
You can also build one step by step.
Keys must be integers or strings. Other types are converted.
| Key you write | Key PHP uses |
|---|---|
"5" (decimal integer string) | integer 5 |
"05" | string "05" |
true / false | 1 / 0 |
null | empty string "" |
7.9 (float) | integer 7, deprecated in PHP 8.1 when precision is lost |
If you repeat a key, the last value wins and the array keeps the position of the first occurrence.
Arrays and objects cannot be keys. You can use enum cases only through their backing value ($case->value).
Reading a missing key gives a warning in PHP 8 ("Undefined array key") and null. Use one of these checks instead.
Use isset() or ?? when a null value means "not set", and array_key_exists() when you must tell a missing key from a null value.
Merging two associative arrays behaves differently depending on the operator.
All three produce theme => dark and lang => en. With integer keys array_merge() renumbers while + keeps the left value.
Plain sort() throws the keys away. Use the functions that preserve them.
| Function | Sorts by | Keeps keys |
|---|---|---|
asort() / arsort() | value ascending / descending | yes |
ksort() / krsort() | key ascending / descending | yes |
uasort() | value, custom comparison | yes |
uksort() | key, custom comparison | yes |
An indexed array uses automatic integer keys starting at 0. An associative array uses keys you pick, usually strings. Both are the same array type internally.
Yes. Elements stay in insertion order, which is guaranteed by the language.
Use array_key_exists('key', $array) to detect the key even with a null value, or isset($array['key']) when null should count as missing.
No. Keys must be integers or strings; using an array as a key throws a TypeError.
An associative array maps named keys to values with key => value pairs. Read with $array['key'], guard with ??, isset() or array_key_exists(), loop with foreach ($array as $key => $value), and use asort(), ksort() and their variants when you need sorting that preserves keys.