Lists of Things: Arrays
One variable, many values
Imagine building a page that lists your five favorite books. With what you know so far, you would need five separate variables: $book1, $book2, and so on. That gets clumsy fast, and it completely falls apart when you do not know in advance how many items there will be. Real websites list products, comments, and search results by the hundreds.
The fix is the array: a single variable that holds a whole list.
Creating an array
<?php
$colors = ["red", "green", "blue"];
?>Square brackets, values separated by commas. Now $colors is one box with three compartments.
Reading items: counting from zero
Each compartment has a number called an index, and here is the part that trips up every newcomer: counting starts at 0, not 1.
<?php
$colors = ["red", "green", "blue"];
echo $colors[0];
echo $colors[1];
echo $colors[2];
?>This prints red, then green, then blue. The first item is at index 0, the second at index 1, and in general the last item of a list with N items lives at index N minus 1. Ask for $colors[3] here and PHP will warn you that nothing is there.
Changing and adding items
<?php
$colors = ["red", "green", "blue"];
$colors[1] = "emerald";
$colors[] = "yellow";
?>The first line after the list replaces green with emerald. The second line uses empty square brackets, which means: stick this on the end. The array now holds red, emerald, blue, yellow.
How many items?
PHP gives you a built-in helper called count():
<?php
$colors = ["red", "emerald", "blue", "yellow"];
echo count($colors);
?>This prints 4. You will use count() all the time: showing 12 results found, checking whether a cart is empty, splitting lists into pages.
Arrays can hold anything
Strings, numbers, even other arrays. A shopping cart might be an array of prices:
<?php
$prices = [19.99, 4.50, 32.00];
echo $prices[0] + $prices[1] + $prices[2];
?>This prints 56.49. Adding up a list item by item like this works, but it is tedious, and it breaks the moment the list grows. Hold that thought: in the loops lesson you will meet foreach, which handles a list of any size in three lines.
The zero thing is worth repeating because it causes so many bugs: the first item is [0], and the last item of a 10-item array is [9]. Say it out loud once. Everyone gets bitten by this exactly once.
Quick check
Q1 Given $animals = ["cat", "dog", "bird"]; what does echo $animals[1]; print?
Q2 What does $list[] = "new item"; do?
Want to save your progress? It's free.
Create a free account