An indexed array is an ordered list of values, each automatically numbered starting from 0 — the same array concept from Intro to Programming, in PHP's specific syntax.
<?php
$fruits = ["apple", "banana", "mango"];
echo $fruits[0]; // "apple"
echo $fruits[2]; // "mango"
?>The older array(...) syntax still works identically to [...] — you'll see both in real code, but square brackets are the modern standard.
<?php
$fruits = ["apple", "banana"];
$fruits[] = "mango"; // appends to the end
$fruits[0] = "green apple"; // overwrites index 0
unset($fruits[1]); // removes "banana" — leaves a gap in the indexes
?>unset() leaves gaps
unset() removes an element but does not renumber the remaining indexes to close the gap. If you need a clean, re-indexed array afterward, wrap it in array_values($fruits).
<?php
$fruits = ["apple", "banana", "mango"];
echo count($fruits); // 3
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>foreach is by far the most common way to loop over a PHP array — you'll see it used constantly from here on. The Loops lesson later in this section covers it, and PHP's other loop types, in full.
An array can hold other arrays, letting you model grid-like or nested data:
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
];
echo $matrix[1][2]; // 6 — second row, third column
?>