Arrays
Lists and key-value data — indexed and associative arrays.
What you will learn
- Create indexed and associative arrays
- Read and loop them
- Use array functions
Indexed arrays
An array holds many values in a single variable — a list. In an indexed array each item has a number called its *index*, and counting starts at 0, not 1. So the first item is at position 0, the second at 1, and so on.
<?php
$colors = ["red", "green", "blue"];
echo $colors[0]; // red
echo count($colors); // 3
$colors[] = "yellow"; // add to the end
?>The list ["red", "green", "blue"] is stored in $colors. $colors[0] reaches in for the item at position 0 — red. count($colors) counts how many items there are — 3. The empty brackets $colors[] = "yellow" mean "append to the end", so the array becomes red, green, blue, yellow.
Note: Output (in the browser):
red3
$colors[0] printed red and count() printed 3, side by side. The $colors[] = "yellow" line only changes the array; it does not print. Remember: the first item is index 0, so the last of four items is index 3.
Associative arrays (key => value)
An associative array uses named keys instead of numbers — perfect for describing one thing (like a user). Each entry is a pair: a key on the left, its value on the right, joined by =>.
<?php
$user = [
"name" => "Asha",
"age" => 22,
"city" => "Bengaluru"
];
echo $user["name"]; // Asha
foreach ($user as $key => $value) {
echo "$key: $value <br>";
}
?>Instead of a number, you look items up by their key: $user["name"] returns Asha. To visit every pair, foreach ($user as $key => $value) hands you both halves each time — $key holds the label (like name) and $value holds its value (like Asha).
Note: Output (in the browser):
Asha
name: Asha
age: 22
city: Bengaluru
First echo $user["name"] printed Asha. Then the foreach looped through all three pairs, printing each key and its value on its own line.
Note: Associative arrays look just like database rows and JSON objects — this is the shape of data your PHP apps will pass around constantly.
Q. How do you define a key in an associative array?
✍️ Practice
- Make an indexed array of subjects and loop it.
- Make an associative array describing a product (name, price) and print each field.
🏠 Homework
- Build an array of three user associative arrays and loop to print them as HTML cards.