CodeMIRAI
0 XP

Associative arrays

2 min read 5 runnable examples Quiz included

An associative array uses named keys instead of numbers: perfect for data with labels, like a person's details.

PHP
<?php
$user = [
    "name" => "Asha",
    "age" => 21,
    "city" => "Mumbai",
];
echo $user["name"], " lives in ", $user["city"], "\n";

$user["email"] = "asha@example.com";   // add
$user["age"] = 22;                     // change
unset($user["city"]);                  // remove
print_r($user);

Under the hood, PHP has a single array type: an indexed array is just one whose keys happen to be 0, 1, 2 and so on.

Does the key exist?

PHP
<?php
$settings = ["theme" => "dark", "beta" => null];

var_dump(isset($settings["theme"]));                // true
var_dump(isset($settings["beta"]));                 // false: the key exists, but its value is null
var_dump(array_key_exists("beta", $settings));      // true
var_dump(array_key_exists("lang", $settings));      // false

echo $settings["lang"] ?? "en", "\n";               // safe default for a missing key

isset is false for missing keys and for keys holding null. When the difference matters, use array_key_exists. Reading a missing key directly prints a warning; ?? avoids it.

Looping

PHP
<?php
$stock = ["apples" => 40, "bananas" => 25, "cherries" => 0];
foreach ($stock as $fruit => $count) {
    $status = $count > 0 ? "$count in stock" : "sold out";
    echo ucfirst($fruit), ": $status\n";
}
echo "Fruits: ", implode(", ", array_keys($stock)), "\n";
echo "Total: ", array_sum(array_values($stock)), "\n";

Sorting

PHP
<?php
$scores = ["Leo" => 78, "Asha" => 92, "Mei" => 85];

ksort($scores);      // by key, A to Z
print_r($scores);
arsort($scores);     // by value, highest first, keeping keys
print_r($scores);
FunctionSorts byOrderKeeps keys?
ksort / krsortkeyascending / descendingyes
asort / arsortvalueascending / descendingyes
sort / rsortvalueascending / descendingno: renumbers from 0

Don't use sort on an associative array: it throws the keys away.

Lists of records

PHP
<?php
$students = [
    ["name" => "Asha", "course" => "PHP", "score" => 92],
    ["name" => "Leo", "course" => "SQL", "score" => 78],
    ["name" => "Mei", "course" => "PHP", "score" => 85],
];

foreach ($students as ["name" => $name, "score" => $score]) {
    echo str_pad($name, 6), $score >= 80 ? "merit" : "pass", "\n";
}

$byCourse = [];
foreach ($students as $s) {
    $byCourse[$s["course"]][] = $s["name"];      // group names by course
}
print_r($byCourse);

An array of associative arrays is how PHP usually holds rows from a database or a JSON file. foreach ($students as ["name" => $name, ...]) destructures each record by key, and $byCourse[$course][] = ... creates each group the first time it's needed.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.