16. PHP Associative Arrays
What you will learn
- What an associative array is
- How to read, add, and remove keys
- How to loop with keys and values
- How to sort, check for keys, and nest arrays
Named keys
An associative array uses names (keys) instead of numbers. It stores data in key and value pairs, such as a person, a product, or a form submission. The arrow => links a key to its value.
PHP code
<?php
$person = [
"name" => "Sam",
"age" => 25,
"city" => "Lahore"
];
echo $person["name"] . " is " . $person["age"] . " and lives in " . $person["city"] . ".";
Output
Sam is 25 and lives in Lahore.
Changing, adding, and removing
PHP code
<?php
$car = ["brand" => "Toyota", "year" => 2020];
$car["year"] = 2024;
$car["color"] = "blue";
unset($car["brand"]);
echo implode(", ", array_keys($car)) . " | color: " . $car["color"];
Output
year, color | color: blue
Looping with keys and values
PHP code
<?php
$lesson = ["title" => "Arrays", "order" => 16, "free" => true];
foreach ($lesson as $key => $value) {
echo $key . " = " . var_export($value, true) . "<br>";
}
What the browser shows
title = ‘Arrays’
order = 16
free = true
var_export() prints a value as PHP code, which is why the text appears in quotes.
Checking for keys safely
Reading a key that does not exist gives a warning. Check first, or use ??.
PHP code
<?php
$user = ["name" => "Sam", "phone" => null];
var_dump(array_key_exists("phone", $user));
var_dump(isset($user["phone"]));
echo $user["email"] ?? "no email";
What you should see
bool(true) bool(false) no email
array_key_exists() is true even when the value is null, while isset() is false for null.
Keys and values
PHP code
<?php
$stock = ["pens" => 40, "books" => 12, "bags" => 5];
echo implode(", ", array_keys($stock)) . "<br>";
echo implode(", ", array_values($stock)) . "<br>";
echo "Total items: " . array_sum($stock);
What the browser shows
pens, books, bags
40, 12, 5
Total items: 57
Sorting by key or value
| Function | Sorts by | Keeps the key link? |
|---|---|---|
asort($a) |
Value, low to high | Yes |
arsort($a) |
Value, high to low | Yes |
ksort($a) |
Key, A to Z | Yes |
krsort($a) |
Key, Z to A | Yes |
PHP code
<?php
$scores = ["Sam" => 72, "Ali" => 90, "Mia" => 85];
arsort($scores);
foreach ($scores as $name => $score) {
echo "$name: $score<br>";
}
What the browser shows
Ali: 90
Mia: 85
Sam: 72
Plain sort() would throw the keys away, so use the a and k versions for associative arrays.
Arrays of associative arrays
Real data is often a list of records.
PHP code
<?php
$products = [
["name" => "Notebook", "price" => 4.5],
["name" => "Pen", "price" => 1.2],
["name" => "Bag", "price" => 18]
];
$total = 0;
foreach ($products as $product) {
echo htmlspecialchars($product["name"]) . ": " . number_format($product["price"], 2) . "<br>";
$total += $product["price"];
}
echo "Total: " . number_format($total, 2);
What the browser shows
Notebook: 4.50
Pen: 1.20
Bag: 18.00
Total: 23.70
array_column($products, "name") pulls one column out as a plain list.
JSON and arrays
PHP converts between arrays and JSON text, which is how data moves to and from JavaScript.
PHP code
<?php
$data = ["name" => "Sam", "skills" => ["HTML", "PHP"]];
$json = json_encode($data);
echo $json . "<br>";
$back = json_decode($json, true);
echo $back["skills"][1];
What the browser shows
{“name”:”Sam”,”skills”:[“HTML”,”PHP”]}
PHP
Pass true to json_decode() to get an associative array instead of an object.
Common mistakes
- Reading a key that does not exist, without
??orisset(). - Misspelling a key, since keys are case sensitive.
- Using
sort()on an associative array and losing the keys. - Forgetting the
=>arrow, or the comma between items. - Printing values from outside without
htmlspecialchars().
Exercise
Create $book with the keys title, author, and pages (320). Print Title by Author (320 pages) using its values.
Show solution
<?php
$book = [
"title" => "Learning Code",
"author" => "Sam Rivera",
"pages" => 320
];
echo $book["title"] . " by " . $book["author"] . " (" . $book["pages"] . " pages)";
Knowledge check
1. Which symbol links a key to its value?
The arrow =>.
2. Which function sorts by value but keeps the keys?
asort() (or arsort() for descending).
3. Which function turns an array into JSON text?
json_encode()
Summary
- Associative arrays store key and value pairs.
- Loop with
foreach ($a as $key => $value), and check keys with??orisset(). - Use
asortandksortto sort, andjson_encodeandjson_decodeto exchange data.