Associative Arrays
An associative array is a PHP array where the keys are meaningful strings instead of auto-generated integers. Rather than referring to "the third element," you refer to the element by name — $user["email"] reads far better than $user[2] and does not break if the order of fields ever changes. Associative arrays are how PHP represents simple records: a single row of configuration, a parsed JSON object, one entry from a form submission.
Creating and reading string-keyed arrays
A record as an associative array
<?php
$user = [
"name" => "Daniela",
"email" => "daniela@example.com",
"age" => 34,
];
echo $user["name"]; // Daniela
echo "\n";
echo $user["email"]; // daniela@example.comDaniela daniela@example.com
Associative arrays as simple maps
Because any string can be a key, associative arrays double as a lightweight lookup table - a map from a code to a label, from a slug to a page title, from a currency symbol to its name. This is a very common pattern for small, fixed sets of data that do not need a database round trip.
A lookup table
<?php
$statusLabels = [
"pending" => "Awaiting review",
"approved" => "Ready to ship",
"rejected" => "Needs changes",
];
$currentStatus = "approved";
echo $statusLabels[$currentStatus]; // Ready to shipReady to ship
array_key_exists() versus isset()
These two functions are often used interchangeably, but they answer subtly different questions. array_key_exists() asks "does this key exist in the array at all?" isset() asks "does this key exist and is its value not null?" If a key's value is explicitly null, isset() reports false even though the key is genuinely present - which is the single most common source of confusion around these two functions.
The null-value distinction
<?php
$profile = [
"name" => "Kenji",
"nickname" => null, // key exists, value is null
];
var_dump(array_key_exists("nickname", $profile)); // bool(true)
var_dump(isset($profile["nickname"])); // bool(false)
var_dump(array_key_exists("phone", $profile)); // bool(false)
var_dump(isset($profile["phone"])); // bool(false)bool(true) bool(false) bool(false) bool(false)
Iterating with foreach and key => value
The foreach ($array as $key => $value) form is the standard way to
walk an associative array when you need both the label and the data.
If you only need the values, you can drop the $key => part
entirely.
Walking key/value pairs
<?php
$prices = ["apple" => 0.50, "banana" => 0.25, "cherry" => 3.00];
foreach ($prices as $fruit => $price) {
echo "{$fruit}: \${$price}\n";
}apple: $0.5 banana: $0.25 cherry: $3
String keys are case-sensitive:
"Name"and"name"are different keys.A numeric string key like
"3"is automatically cast to the integer3by PHP -$arr["3"]and$arr[3]refer to the same slot.Associative arrays preserve insertion order, so
foreachalways visits entries in the order they were added or last re-assigned.You can freely mix reading and writing keys that do not exist yet - assigning to a new key simply adds it.