iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Indexed Arrays

An indexed array stores values under sequential integer keys starting at 0. PHP's most list-like collection.

Create

PHP
$cars = ['Volvo', 'BMW', 'Toyota'];

// Equivalent legacy syntax
$cars = array('Volvo', 'BMW', 'Toyota');

Access

PHP
echo $cars[0];     // Volvo
echo $cars[2];     // Toyota
echo count($cars); // 3

Add & remove

PHP
$cars[] = 'Tesla';        // append — index becomes 3
array_push($cars, 'Audi'); // same idea

$last  = array_pop($cars);    // remove and return the last
$first = array_shift($cars);  // remove and return the first

array_unshift($cars, 'Bentley');  // prepend

Iterate

PHP
foreach ($cars as $car) {
    echo $car, PHP_EOL;
}

foreach ($cars as $i => $car) {
    echo "$i: $car", PHP_EOL;
}

Watch for "gaps"

unset($arr[1]) removes the entry but leaves the others' indexes alone:

PHP
$arr = ['a', 'b', 'c'];
unset($arr[1]);
print_r($arr);          // [0 => 'a', 2 => 'c'] — note gap

$arr = array_values($arr);  // reindex to [0 => 'a', 1 => 'c']
Tip: PHP 8.1+ has array_is_list() — quickly check whether an array is a clean 0-based indexed list with no gaps.

Example

Example
<?php
$cars = ['Volvo', 'BMW', 'Toyota'];
echo $cars[0], PHP_EOL;
echo count($cars), PHP_EOL;
Try it Yourself »

Exercise

Count elements with…

($cars)

Test yourself

Q1. Indexed arrays start at…
Q2. Reindex after unset using…
Q3. Append idiom is…

Discussion

Loading…