Associative Arrays

Labeling your data instead of numbering it

8 min read

Numbered lists are great when the items are all the same kind of thing, like a list of colors. But look at this attempt to describe a product:

<?php
$product = ["Coffee Mug", 12.50, 34];
?>

Quick, what is 34? The stock count? A discount? The number of reviews? You cannot tell, and neither will you in three weeks when you reread this code. Position numbers are a terrible way to describe different pieces of information about one thing.

Keys instead of numbers

An associative array lets you replace the automatic numbers with labels of your own choosing, called keys:

<?php
$product = [
    "name" => "Coffee Mug",
    "price" => 12.50,
    "stock" => 34
];
?>

The => arrow pairs each key with its value: the key "name" points to "Coffee Mug", and so on. Now the data documents itself. No guessing what 34 means.

Reading and writing by key

<?php
echo $product["name"];
echo "Only " . $product["stock"] . " left!";
$product["stock"] = 33;
$product["color"] = "blue";
?>

Reading works just like numbered arrays, except you use the key in the brackets. Assigning to an existing key updates its value, and assigning to a brand new key, like "color" here, adds a fresh pair to the array.

Arrays inside arrays

Here is where things get genuinely powerful. A numbered list can hold associative arrays, which is exactly the shape of almost every real web page you have ever seen:

<?php
$products = [
    ["name" => "Coffee Mug", "price" => 12.50],
    ["name" => "Tea Pot", "price" => 29.00],
    ["name" => "Spoon Set", "price" => 8.75]
];
echo $products[1]["name"];
?>

This prints Tea Pot. Read $products[1]["name"] from left to right: go to item 1 of the list, then grab its name. A product listing, a comment thread, a search results page, all of them are a list of labeled records, exactly like this.

Remember this shape: a numbered array of associative arrays. When you reach the database lesson at the end of this course, you will discover that query results arrive in exactly this form. Learning it now means the database will feel familiar later.

One habit to build early: choose key names as carefully as variable names. "price" beats "p", and consistency across your project, always "name", never sometimes "title" for the same idea, saves real headaches.

Quick check

Q1 Given $user = ["name" => "Sam", "age" => 30]; how do you print Sam?

Q2 What does the => arrow do inside an array?

Want to save your progress? It's free.

Create a free account