Key-value pairs
Learn to create associative arrays with key-value pairs.
What is an associative array?
An associative array stores values under keys instead of numeric indexes. Each entry is a key-value pair; the key is a string and the value can be any type.
For example you can describe a user with $user = ["name" => "Alex", "age" => 28]. Here "name" and "age" are keys, while "Alex" and 28 are their values. Associative arrays work like a dictionary or a map.
The key-value arrow
In an associative array you write each pair with the => arrow: "key" => value. The key sits on the left of the arrow, the value on the right. Pairs are separated by commas and placed inside square brackets.
Both array() and [] syntax work for associative arrays; the short [] form is common in modern PHP. Keys are written inside single or double quotes.
Exercise Product array and price
Create the $product associative array. Keys: name, price, stock. Values: Keyboard, 1200, 15. Then print the price with echo.
Show example solution
Put the three keys inside square brackets separated by commas; then write echo $product["price"] . "\n";
Example solution:
<?php
// Define the product and print its price
$product = [
"name" => "Keyboard",
"price" => 1200,
"stock" => 15
];
echo $product["price"] . "\n";
Test yourself
-
Which one accesses the value "Alex"?
$user = ["name" => "Alex", "age" => 28];- $user[0]
- $user["name"]
- $user[name]
- $user->name
Show answer
$user["name"] — Correct. You reach the value with the "name" key; the result is "Alex".
-
Write the arrow
$user = ["name" ____ "Alex"];Show answer
$user = ["name" => "Alex"]; -
What does the code below print?
$book = ["title" => "Les Misérables", "year" => 1862]; echo $book["title"];- Les Misérables
- 1862
- title
- book
Show answer
Les Misérables — Correct. The value of the "title" key is "Les Misérables", so that is printed.