Skip to content

PHP Tutorial Arrays

Indexed Arrays

Lesson 118 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

An indexed array is an ordered list. Each item has a number called its index, starting at 0.

index.php
PHP
<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo $fruits[0] . "\n";
echo $fruits[1] . "\n";
echo $fruits[2];
Output
OUTPUT
Apple
Banana
Cherry

Think of a row of numbered lockers: locker 0, locker 1, locker 2.

Ways to create one

index.php
PHP
<?php
$a = ["red", "green"];       // short syntax, the one to use
$b = array("red", "green");  // older syntax, same result
$c = [];                     // empty array

var_dump($a === $b);
var_dump(count($c));
Output
OUTPUT
bool(true)
int(0)

Change an item

index.php
PHP
<?php
$colors = ["red", "green", "blue"];

$colors[1] = "yellow";

echo implode(", ", $colors);
Output
OUTPUT
red, yellow, blue

Add an item to the end

Use empty square brackets.

index.php
PHP
<?php
$tasks = ["Wash", "Cook"];

$tasks[] = "Clean";

echo implode(", ", $tasks);
Output
OUTPUT
Wash, Cook, Clean

Loop through the list

index.php
PHP
<?php
$tasks = ["Wash", "Cook", "Clean"];

foreach ($tasks as $index => $task) {
    echo ($index + 1) . ". " . $task . "\n";
}
Output
OUTPUT
1. Wash
2. Cook
3. Clean

Reading a missing index

index.php
PHP
<?php
$tasks = ["Wash"];

echo $tasks[5] ?? "No such task";
Output
OUTPUT
No such task

Without ??, PHP raises the warning Undefined array key 5.

index.php
PHP
<?php
$numbers = [10, 20, 30];

print_r($numbers);
var_dump($numbers);
Output
OUTPUT
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
array(3) {
  [0]=>
  int(10)
  [1]=>
  int(20)
  [2]=>
  int(30)
}

Last item

index.php
PHP
<?php
$items = ["a", "b", "c"];

echo $items[count($items) - 1] . "\n";
echo end($items) . "\n";
echo $items[array_key_last($items)];
Output
OUTPUT
c
c
c

Exercise: a playlist

Create an array of four song names. Print the second one, replace the last with a new name, add a fifth, and print how many songs there are.

Show a possible solution
index.php
PHP
<?php
$songs = ["Sunrise", "River", "Blue Hour", "Echo"];

echo $songs[1] . "\n";
$songs[3] = "Wildflower";
$songs[] = "Home";

echo count($songs);
Output
OUTPUT
River
5