PHP Associative Arrays

Associative arrays pair each value with a meaningful name instead of a number, so your data reads like a labelled record.

Keys with meaning

In an associative array you choose the key for every value, using a descriptive string instead of an automatic number. This makes the array behave like a small record or dictionary, where each label points to a piece of information. Associative arrays are everywhere in PHP: configuration settings, database rows, and decoded JSON all arrive as associative arrays.

Building an associative array

<?php
$user = [
    "name"  => "Aisha",
    "email" => "aisha@example.com",
    "age"   => 29,
];

echo $user["name"];   // Aisha
echo $user["age"];    // 29
?>

The => symbol assigns a value to a key. You add or update an entry by assigning to a named key, and PHP will create the key if it does not yet exist or replace the value if it does.

Adding and updating entries

<?php
$settings = ["theme" => "dark"];

$settings["language"] = "en";   // new entry
$settings["theme"] = "light";   // updates existing entry

print_r($settings);
// [theme => light, language => en]
?>

Looping with keys and values

Because the interesting part of an associative array is the pairing of key and value, the foreach loop supports a special form that gives you both at once.

foreach with key and value

<?php
$prices = [
    "coffee" => 3.50,
    "tea"    => 2.75,
    "juice"  => 4.00,
];

foreach ($prices as $item => $price) {
    echo "$item costs $" . $price . "\n";
}
?>
Note: If two entries share the same key, the later one wins and silently overwrites the earlier value. Keys are unique within a single array.

Checking and removing entries

  • Use isset($arr["key"]) to test whether a key exists and is not null.
  • Use array_key_exists("key", $arr) when you must detect a key whose value is null.
  • Use unset($arr["key"]) to remove a single entry.
  • Use array_keys($arr) and array_values($arr) to pull out just the labels or just the data.
Note: isset() returns false when a key exists but its value is null, whereas array_key_exists() returns true. Choose array_key_exists() when null is a legitimate stored value you need to distinguish from a missing key.

Safe access with a default

<?php
$config = ["host" => "localhost"];

// Null coalescing supplies a fallback when the key is missing
$port = $config["port"] ?? 8080;

echo $port;   // 8080
?>