How to loop through an array with an index
Short answer
foreach can give you both the key and the value:
<?php
foreach (['a', 'b', 'c'] as $index => $value) {
echo "$index: $value\n";
}Output:
0: a
1: b
2: cNumbering from one
Indexes start at zero. Add one for human-friendly numbering:
<?php
foreach (['tea', 'milk'] as $index => $item) {
echo $index + 1, '. ', $item, "\n";
}Output:
1. tea
2. milkAssociative arrays
The same syntax works with string keys:
<?php
foreach (['name' => 'Anna', 'age' => 25] as $key => $value) {
echo "$key = $value\n";
}Output:
name = Anna
age = 25Functions used in this recipe
- count — Returns the number of elements in an array.
- array_keys — Returns all the keys of an array.