Arrays
A PHP array is an ordered, numerically-indexed list of values that can grow or shrink after it's created — and under the hood, it's the exact same data structure that powers the associative arrays in the next lesson.
Creating and reading an array
<?php $colors = ["red", "green", "blue"]; echo $colors[0] . "\n"; echo $colors[2] . "\n"; echo count($colors) . "\n"; ?>
red blue 3
The square-bracket [...] syntax is the modern way to write an array literal (the older array(...) function still works and means exactly the same thing). Indexing starts at 0, and count() gives the number of elements.
Adding, updating, and removing items
<?php $colors = ["red", "green", "blue"]; $colors[] = "yellow"; array_push($colors, "purple"); $colors[0] = "crimson"; unset($colors[1]); print_r($colors); ?>
Array
(
[0] => crimson
[2] => blue
[3] => yellow
[4] => purple
)
$colors[] = "yellow" is the idiomatic way to append — the empty brackets mean "next available index." array_push() does the same thing but can add several items at once. unset() removes an element by key, but notice it leaves a gap: index 1 is simply gone rather than everything shifting down, which is why the remaining keys read 0, 2, 3, 4 instead of 0, 1, 2, 3.
array_values($colors), which returns a fresh array with sequential keys starting from 0.Sorting
<?php $scores = [88, 42, 95, 67]; sort($scores); print_r($scores); rsort($scores); print_r($scores); ?>
Array
(
[0] => 42
[1] => 67
[2] => 88
[3] => 95
)
Array
(
[0] => 95
[1] => 88
[2] => 67
[3] => 42
)
sort() rearranges ascending, rsort() descending — and both work in place on the array itself and re-index the keys from 0, rather than returning a new array.
Checking membership and merging
<?php $a = [1, 2, 3]; $b = [3, 4, 5]; var_dump(in_array(2, $a)); $merged = array_merge($a, $b); print_r($merged); ?>
bool(true)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 3
[4] => 4
[5] => 5
)
array_merge() concatenates indexed arrays end to end and renumbers the keys — it does not remove duplicates, so the 3 that both arrays share appears twice in the result.