An Indexed Array (also known as a numeric array) is an ordered collection where each value is automatically assigned a numeric index starting at 0. Indexed arrays are the standard choice whenever you need to maintain an ordered list of items, such as a list of blog post titles, product IDs, or student examination scores.
You can create an indexed array automatically using sequential assignment or by explicitly assigning specific indices:
<?php
// Auto-indexed assignment (Index 0, 1, 2)
$cars = ["Volvo", "BMW", "Toyota"];
// Explicit manual indexing
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
// Accessing elements via numeric index:
echo "First car: " . $cars[0] . "<br>"; // Volvo
echo "Second car: " . $cars[1] . "<br>"; // BMW
?>
You can add new items to the end of an indexed array using empty square brackets [] or replace an existing element by specifying its index:
<?php
$cities = ["Delhi", "Mumbai", "Kolkata"];
// Appending an item to the end
$cities[] = "Chennai"; // Automatically assigned index 3
array_push($cities, "Pune"); // Appended at index 4
// Modifying an existing item
$cities[0] = "New Delhi"; // Replaces "Delhi" at index 0
print_r($cities);
?>
for vs foreach<?php
$scores = [78, 85, 92, 64, 88];
// Method 1: Using for loop with count()
$total = count($scores);
for ($i = 0; $i < $total; $i++) {
echo "Score at index [$i] = " . $scores[$i] . "<br>";
}
// Method 2: Using foreach loop (Cleaner & Safer)
foreach ($scores as $index => $score) {
echo "Student #$index earned: $score%<br>";
}
?>
sort() and rsort()| Function | Sorting Order | Example |
|---|---|---|
sort($arr) |
Ascending Order (A-Z, 0-9) | $nums = [5, 2, 8]; sort($nums); // [2, 5, 8] |
rsort($arr) |
Descending Order (Z-A, 9-0) | $nums = [5, 2, 8]; rsort($nums); // [8, 5, 2] |
High-Frequency Exam Question:
Q: What happens if an element is deleted with unset($arr[1]) from an indexed array?
A: unset() deletes the element and its key, but does NOT re-index the array (leaving a gap, e.g. keys 0, 2, 3). To re-index the numeric keys sequentially from 0, call $arr = array_values($arr);.
Exercise 22.1: Create an array of 5 student marks. Sort them in descending order and calculate the highest and lowest scores using max() and min().
Exercise 22.2: Write a script that removes duplicate values from an indexed array using array_unique().