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 arrays.php
<?php
$colors = ["red", "green", "blue"];

echo $colors[0] . "\n";
echo $colors[2] . "\n";
echo count($colors) . "\n";
?>
Output
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 editing.php
<?php
$colors = ["red", "green", "blue"];

$colors[] = "yellow";
array_push($colors, "purple");
$colors[0] = "crimson";
unset($colors[1]);

print_r($colors);
?>
Output
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.

Note: if you need the keys re-numbered cleanly after removing items, wrap the array in array_values($colors), which returns a fresh array with sequential keys starting from 0.

Sorting

PHP sorting.php
<?php
$scores = [88, 42, 95, 67];

sort($scores);
print_r($scores);

rsort($scores);
print_r($scores);
?>
Output
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 membership.php
<?php
$a = [1, 2, 3];
$b = [3, 4, 5];

var_dump(in_array(2, $a));
$merged = array_merge($a, $b);
print_r($merged);
?>
Output
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.