An indexed array is an ordered list. Each item has a number called its index, starting at 0.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0] . "\n";
echo $fruits[1] . "\n";
echo $fruits[2];
Apple
Banana
Cherry
Think of a row of numbered lockers: locker 0, locker 1, locker 2.
Ways to create one
<?php
$a = ["red", "green"]; // short syntax, the one to use
$b = array("red", "green"); // older syntax, same result
$c = []; // empty array
var_dump($a === $b);
var_dump(count($c));
bool(true)
int(0)
Change an item
<?php
$colors = ["red", "green", "blue"];
$colors[1] = "yellow";
echo implode(", ", $colors);
red, yellow, blue
Add an item to the end
Use empty square brackets.
<?php
$tasks = ["Wash", "Cook"];
$tasks[] = "Clean";
echo implode(", ", $tasks);
Wash, Cook, Clean
Loop through the list
<?php
$tasks = ["Wash", "Cook", "Clean"];
foreach ($tasks as $index => $task) {
echo ($index + 1) . ". " . $task . "\n";
}
1. Wash
2. Cook
3. Clean
Reading a missing index
<?php
$tasks = ["Wash"];
echo $tasks[5] ?? "No such task";
No such task
Without ??, PHP raises the warning Undefined array key 5.
Print the whole array
<?php
$numbers = [10, 20, 30];
print_r($numbers);
var_dump($numbers);
Array
(
[0] => 10
[1] => 20
[2] => 30
)
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
Last item
<?php
$items = ["a", "b", "c"];
echo $items[count($items) - 1] . "\n";
echo end($items) . "\n";
echo $items[array_key_last($items)];
c
c
c
Exercise: a playlist
Create an array of four song names. Print the second one, replace the last with a new name, add a fifth, and print how many songs there are.
Show a possible solution
<?php
$songs = ["Sunrise", "River", "Blue Hour", "Echo"];
echo $songs[1] . "\n";
$songs[3] = "Wildflower";
$songs[] = "Home";
echo count($songs);
River
5