Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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: c

Numbering 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. milk

Associative 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 = 25

Functions used in this recipe

  • count — Returns the number of elements in an array.
  • array_keys — Returns all the keys of an array.

Thanks for reading!

Donate to the site — we work hard for you.