Arrays
The array is PHP's workhorse. A single type serves as a list, a dictionary, a stack, a queue and a table of rows from a database. This lesson starts with indexed arrays — ordered lists numbered from 0 — and how to create, read, change, count and loop over them.
Creating an array
Write the values in square brackets, separated by commas. Each element gets a numeric key (an index) starting at 0:
<?php $fruits = ["apple", "banana", "cherry"]; $scores = [72, 95, 88]; $empty = []; $mixed = [1, "two", 3.0, true]; // any types can be mixed echo $fruits[0], "\n"; echo $scores[2], "\n"; echo count($fruits), "\n"; var_dump($empty === []); print_r($mixed);
apple
88
3
bool(true)
Array
(
[0] => 1
[1] => two
[2] => 3
[3] => 1
)The older syntax array("apple", "banana") does the same thing; you'll see it in older code.
Reading and changing elements
<?php $seats = ["Ana", "Ben", "Chen", "Dara"]; echo $seats[1], "\n"; echo $seats[count($seats) - 1], "\n"; $seats[1] = "Bilal"; // replace $seats[] = "Eli"; // append to the end echo implode(", ", $seats), "\n"; echo count($seats), "\n";
Ben Dara Ana, Bilal, Chen, Dara, Eli 5
$array[] = value appends — you'll use it constantly to build arrays in loops. Unlike strings, arrays don't support negative indexes like $seats[-1]; to get the last element, use array_last() (PHP 8.5) or end().
Missing elements
Reading an index that doesn't exist gives a warning and null. Check with isset or array_key_exists, or use ?? for a default:
<?php $colours = ["red", "green"]; echo $colours[5] ?? "(none)", "\n"; var_dump(isset($colours[1]), isset($colours[5])); echo $colours[5];
(none) bool(true) bool(false) Warning: Undefined array key 5 in main.php on line 7
Building arrays in loops
<?php $squares = []; for ($i = 1; $i <= 5; $i++) { $squares[] = $i * $i; } echo implode(" ", $squares), "\n"; $long = []; foreach (["kiwi", "banana", "fig", "cherry"] as $fruit) { if (strlen($fruit) > 4) { $long[] = $fruit; } } echo implode(", ", $long), "\n";
1 4 9 16 25 banana, cherry
Lesson 23 shows array_map and array_filter, which do the same jobs in one line.
Adding and removing at the ends
Four functions treat an array like a stack or a queue:
<?php $queue = ["b", "c"]; array_push($queue, "d", "e"); // add to the end array_unshift($queue, "a"); // add to the start echo implode(" ", $queue), "\n"; $last = array_pop($queue); // remove from the end $first = array_shift($queue); // remove from the start echo "removed $first and $last: ", implode(" ", $queue), "\n";
a b c d e removed a and e: b c d
Removing from the middle
unset removes an element but leaves a gap in the keys. array_values renumbers them; array_splice removes and renumbers in one go:
<?php $letters = ["a", "b", "c", "d"]; unset($letters[1]); print_r($letters); print_r(array_values($letters)); $nums = [10, 20, 30, 40, 50]; array_splice($nums, 1, 2); // remove 2 elements from index 1 echo implode(" ", $nums), "\n"; array_splice($nums, 1, 0, [15, 18]); // insert without removing echo implode(" ", $nums), "\n";
Array
(
[0] => a
[2] => c
[3] => d
)
Array
(
[0] => a
[1] => c
[2] => d
)
10 40 50
10 15 18 40 50Searching
<?php $temps = [18, 22, 25, 19, 30, 22]; var_dump(in_array(25, $temps, true)); var_dump(array_search(22, $temps, true)); // first matching key var_dump(array_search(99, $temps, true)); echo max($temps), " ", min($temps), " ", array_sum($temps) / count($temps), "\n"; echo array_first($temps), " ", array_last($temps), "\n";
bool(true) int(1) bool(false) 30 18 22.666666666667 18 22
Pass true as the third argument to in_array and array_search for strict comparison. And as with strpos, array_search can return key 0, so compare its result with !== false. array_first and array_last are new in PHP 8.5.
Slicing and combining
<?php $months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]; echo implode(" ", array_slice($months, 2, 3)), "\n"; echo implode(" ", array_slice($months, -2)), "\n"; $more = ["Jul", "Aug"]; echo implode(" ", array_merge($months, $more)), "\n"; echo implode(" ", [...$months, ...$more]), "\n"; // spread (lesson 26) echo implode(" ", array_reverse($more)), "\n";
Mar Apr May May Jun Jan Feb Mar Apr May Jun Jul Aug Jan Feb Mar Apr May Jun Jul Aug Aug Jul
Arrays are copied on assignment
Assigning an array to another variable, or passing it to a function, gives an independent copy. (PHP is clever about this: it only actually copies when one of them is modified.)
<?php $original = [1, 2, 3]; $copy = $original; $copy[0] = 100; echo implode(",", $original), " / ", implode(",", $copy), "\n"; function addItem(array $list): array { $list[] = "new"; return $list; } $items = ["a"]; $result = addItem($items); echo count($items), " vs ", count($result), "\n";
1,2,3 / 100,2,3 1 vs 2
Try it yourself
Find the hottest and coldest days of the week and the average temperature.
Hottest: Sun (23.1 °C) Coldest: Fri (16.5 °C) Average: 19.8 °C