PHP example

How to loop with an index in PHP

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Ask foreach for the key: foreach ($items as $i => $item). For a list the key is the 0-based index. When the keys have gaps or are strings, count positions yourself with a $pos++ counter or loop over array_values($items). To spot the first and last iteration, compare the key with array_key_first($items) and array_key_last($items) (PHP 7.3 and later).

PHP has no enumerate and no index variable built into foreach, because it doesn't need one: every array is an ordered map, and foreach hands you the key of each element along with its value. For a plain list that key is the index. The catch is that a key is not always a position: after array_filter or unset a list has gaps, and an associative array has string keys. The sections below cover the key-as-index pattern, what to do when the keys are not positions, the classic for loop, first and last iteration, break and continue, and changing the array while you loop over it, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1foreach with the keyRecommended

Write $key => $value after as and foreach fills both variables on every pass. An array literal like ['apple', 'banana'] gets the keys 0, 1, 2 and so on, so the key is the index and you don't need a counter or array_search. The same syntax gives the string key of an associative array, which is why it is the one loop to reach for first.

foreach_index.php
<?php

$fruits = ['apple', 'banana', 'cherry'];

// The key of a list is its 0-based index
foreach ($fruits as $i => $fruit) {
    echo "$i: $fruit\n";
}

// Show 1-based numbers to people, keep $i for code
foreach ($fruits as $i => $fruit) {
    echo ($i + 1) . ". $fruit\n";
}

// The same syntax gives the key of an associative array
$stock = ['apple' => 12, 'banana' => 0, 'cherry' => 40];
foreach ($stock as $name => $count) {
    echo "$name => $count\n";
}

Output

The first loop prints 0: apple through 2: cherry: the keys PHP assigned when it built the list. For numbered output, add one when you print (1. apple) rather than shifting the keys, so $i still matches $fruits[$i]. On $stock the key is the name, as in apple => 12; for the position of an entry in an associative array, see the next section.

2When the key is not a position

array_filter, unset and array_unique keep the original keys, so a filtered list has holes in its numbering. The key is still a correct key, but it is no longer "the second item". When you need a position, either count it yourself with a variable you increment at the end of the loop body, or renumber the keys with array_values first. array_is_list (PHP 8.1) tells you whether the keys are already 0, 1, 2 with no gaps.

position_counter.php
<?php

$scores = [90, 45, 72, 38, 88];

// array_filter keeps the original keys, so the list now has gaps
$passed = array_filter($scores, fn(int $s): bool => $s >= 50);
var_dump(array_is_list($passed));

foreach ($passed as $key => $score) {
    echo "key $key: $score\n";
}
echo 'count - 1 = ' . (count($passed) - 1)
    . ', last key = ' . array_key_last($passed) . "\n";

// Fix 1: count positions yourself
$pos = 0;
foreach ($passed as $score) {
    echo "position $pos: $score\n";
    $pos++;
}

// Fix 2: renumber the keys with array_values
foreach (array_values($passed) as $i => $score) {
    echo "index $i: $score\n";
}

// An associative array has no numeric index at all
$ages = ['ann' => 31, 'bob' => 27];
$n = 0;
foreach ($ages as $name => $age) {
    echo "#$n $name is $age\n";
    $n++;
}

Output

After the filter the keys are 0, 2 and 4, and array_is_list returns bool(false). That breaks any code that treats the key as a position: count - 1 = 2, last key = 4, so a $i === count($passed) - 1 test never fires. Both fixes give the positions 0, 1, 2. Use the counter when you also need the original key (it can sit next to $key => $score), and array_values when you don't. For string keys a counter is the only way to get a number: #0 ann is 31, #1 bob is 27.

3A classic for loop

A for loop makes the index the thing you control, which is what you want when you step by 2, walk backwards, or compare each element with its neighbor. Call count() once before the loop rather than in the condition, where it runs on every pass. Only use it on a list: $items[$i] assumes the keys are 0 to count - 1, which is not true after a filter or for string keys.

for_index.php
<?php

$letters = ['a', 'b', 'c', 'd', 'e', 'f'];

// Store count() once instead of calling it on every pass
$n = count($letters);
$out = [];
for ($i = 0; $i < $n; $i++) {
    $out[] = "$i:{$letters[$i]}";
}
echo implode(' ', $out) . "\n";

// Step by 2: pairs of neighbors
$pairs = [];
for ($i = 0; $i < $n - 1; $i += 2) {
    $pairs[] = $letters[$i] . $letters[$i + 1];
}
echo implode(' ', $pairs) . "\n";

// Backwards, from the last index down to 0
for ($i = $n - 1; $i >= 0; $i--) {
    echo $letters[$i];
}
echo "\n";

// Compare each element with the one before it
$temps = [12, 15, 11, 18];
for ($i = 1, $m = count($temps); $i < $m; $i++) {
    $diff = $temps[$i] - $temps[$i - 1];
    echo "day $i: " . sprintf('%+d', $diff) . "\n";
}

Output

$i += 2 gives the pairs ab cd ef, counting down from $n - 1 prints fedcba, and starting at 1 lets each pass read $temps[$i - 1] for the change from the day before (day 2: -4). The last loop shows the other way to hoist the count: a second variable in the first part of the for, $m = count($temps). Run the first loop on the filtered list from section 2 and PHP prints Warning: Undefined array key 1, because that key does not exist.

4First and last iteration

To treat the first or last element differently, look up its key before the loop and compare. array_key_first and array_key_last (PHP 7.3) work on any array, lists with gaps and associative arrays included, and don't move the internal pointer. For a list you know has no gaps, $i === 0 and $i === count($items) - 1 say the same thing. And if all you want is a separator between items, don't check for the last one at all: that is what implode does.

first_last.php
<?php

$steps = ['checkout', 'build', 'test', 'deploy'];

// Works for any array, including associative ones (PHP 7.3+)
$first = array_key_first($steps);
$last = array_key_last($steps);
foreach ($steps as $key => $step) {
    if ($key === $first) {
        echo "start: $step\n";
    } elseif ($key === $last) {
        echo "finish: $step\n";
    } else {
        echo "  then: $step\n";
    }
}

// For a list, compare the index with 0 and count() - 1
$colors = ['red', 'green', 'blue'];
$lastIndex = count($colors) - 1;
foreach ($colors as $i => $color) {
    echo $color . ($i === $lastIndex ? "\n" : ', ');
}

// Only need separators between items? implode does it for you
echo implode(', ', $colors) . "\n";
echo implode(', ', array_slice($colors, 0, -1)) . ' and '
    . end($colors) . "\n";

// Associative arrays work the same way
$prices = ['tea' => 3, 'cake' => 5];
$lastItem = array_key_last($prices);
foreach ($prices as $item => $price) {
    $mark = $item === $lastItem ? ' (last)' : '';
    echo "$item: $price$mark\n";
}

Output

The steps print as start: checkout, two then lines and finish: deploy. The hand-written separator loop and implode(', ', $colors) both give red, green, blue, and the array_slice version handles the "and" before the last item: red, green and blue. On PHP 8.5, array_first and array_last return the values themselves; for the older ways to get them, see getting the first and last element.

5break, continue and break 2

continue skips the rest of the body and moves on to the next element; break leaves the loop. Both apply to the loop around them, never to an if, so a break inside an if inside a foreach ends the foreach. Inside nested loops, give a number to leave more than one: break 2 ends the inner and the outer loop, and continue 2 jumps to the next pass of the outer one.

break_continue.php
<?php

$orders = [120, 0, 75, -1, 300];

// continue skips to the next item, break leaves the loop
foreach ($orders as $i => $amount) {
    if ($amount === 0) {
        continue;
    }
    if ($amount < 0) {
        echo "stop at index $i\n";
        break;
    }
    echo "order $i: $amount\n";
}

// Find the index of the first match, then stop looking
$names = ['ann', 'bob', 'cleo', 'bob'];
$found = null;
foreach ($names as $i => $name) {
    if ($name === 'bob') {
        $found = $i;
        break;
    }
}
echo "first bob at $found\n";
var_dump(array_search('bob', $names, true));

// break 2 leaves both loops at once
$grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
foreach ($grid as $row => $cells) {
    foreach ($cells as $col => $value) {
        if ($value === 5) {
            echo "5 is at row $row, col $col\n";
            break 2;
        }
    }
}
echo "done\n";

Output

The zero order is skipped, the -1 stops the loop (stop at index 3), and 300 is never reached. Note that the printed indexes stay 0 and 2: continue skips an element but the key still belongs to it. For a plain "where is the first match" search, array_search with true for strict comparison returns the same int(1) without a loop, or false when nothing matches. In the grid, break 2 ends both loops at the first 5 and execution goes straight to done.

6Changing the array while you loop

foreach by value walks over a copy of the array, so assigning to the loop variable changes nothing, and items you append are not visited. To change the elements, write back through the key with $items[$i] = …, or loop by reference with &$item. A reference has a well-known trap: after the loop, the variable still points at the last element, and the next foreach that reuses the name overwrites it on every pass. Call unset() on the variable right after a by-reference loop.

modify_in_loop.php
<?php

$prices = [10, 20, 30];

// foreach loops over a copy: changing $price changes nothing
foreach ($prices as $price) {
    $price *= 2;
    $prices[] = 0;  // and new items are not visited either
}
echo implode(' ', $prices) . "\n";

// Write back through the index
$prices = [10, 20, 30];
foreach ($prices as $i => $price) {
    $prices[$i] = $price * 2;
}
echo implode(' ', $prices) . "\n";

// Or loop by reference with &
$tags = ['php', 'loop', 'index'];
foreach ($tags as &$tag) {
    $tag = strtoupper($tag);
}
echo implode(' ', $tags) . "\n";

// The trap: $tag still points at the last element, so the next
// loop that reuses the name writes into it on every pass
foreach ($tags as $i => $tag) {
    echo "$i=$tag\n";
}
echo implode(' ', $tags) . "\n";

// The fix: unset the reference right after the loop
$words = ['a', 'b', 'c'];
foreach ($words as &$word) {
    $word .= '!';
}
unset($word);
foreach ($words as $word) {
    // reusing $word is safe now
}
echo implode(' ', $words) . "\n";

// array_walk passes the value by reference and the key
array_walk($words, function (string &$w, int $i): void {
    $w = "$i:$w";
});
echo implode(' ', $words) . "\n";

// array_map with array_keys builds a new array from both
$names = ['ann', 'bob'];
$labels = array_map(
    fn(int $i, string $n): string => ($i + 1) . ". $n",
    array_keys($names),
    $names,
);
echo implode(' | ', $labels) . "\n";

Output

The first line, 10 20 30 0 0 0, shows both sides of the copy: the prices did not double, and the three appended zeros were not looped over. Writing back through $prices[$i] gives 20 40 60. Then the bug: the second loop over $tags prints 2=LOOP instead of 2=INDEX, and the array ends up as PHP LOOP LOOP, with the last element replaced by a copy of the one before it. Each pass assigned to $tag, which was still a reference to $tags[2]. With unset($word) the second loop is harmless and a! b! c! survives. array_walk hands its callback the key as the second argument, and array_map gets the keys when you pass array_keys($names) as an extra array.

7Which should you use?

MethodGives youBest for
foreach ($a as $i => $v)The keyLists and associative arrays: almost every loop
$pos = 0; ... $pos++PositionGaps or string keys, when you also need the key
foreach (array_values($a) ...)PositionGaps after array_filter or unset, keys not needed
for ($i = 0; $i < $n; $i++)Index you controlStepping by 2, going backwards, comparing neighbors
array_key_first / array_key_lastFirst and last keySpecial-casing the first or last iteration (7.3+)
implode(', ', $a)A joined stringSeparators between items, no loop needed
foreach ($a as &$v)A referenceChanging elements in place; unset($v) afterward

Frequently asked questions

Does PHP have an enumerate function like Python?

No, and it does not need one. foreach ($items as $i => $item) gives you the key and the value together, and for a list the key is the 0-based index. When the keys are not 0, 1, 2 (after array_filter, or for string keys), loop over array_values($items) or keep a counter.

How do I get the index of a foreach loop over a generator?

The same way: foreach (lines() as $i => $line). A generator that yields plain values gets the keys 0, 1, 2 automatically, so a generator yielding alpha, beta and gamma prints 0: alpha, 1: beta, 2: gamma. If the generator uses yield $key => $value, you get its own keys instead.

Why does my for loop print "Undefined array key"?

The array is not a list with keys 0 to count - 1. After array_filter or unset, the keys have gaps, so $items[$i] asks for a key that is gone, and PHP prints Warning: Undefined array key 1 and gives null. Use foreach, or renumber the keys first with array_values.

Why is the last element duplicated after a foreach by reference?

After foreach ($a as &$v) the variable $v is still a reference to the last element. A later foreach ($a as $v) assigns each element to $v, which writes into that last slot every time, so ['PHP', 'LOOP', 'INDEX'] ends up as PHP LOOP LOOP. Put unset($v); right after the by-reference loop, or use a different variable name in the second loop.

How do I find the last iteration on PHP older than 7.3?

For a list, compare the index with count($items) - 1. For any array, move the internal pointer with end($items) and read the key with key($items), then call reset($items); for ['p' => 1, 'q' => 2] that gives "q". From PHP 7.3 use array_key_last($items), which does not touch the pointer.

How do I break out of an if inside a foreach?

break does not apply to if; it always ends the innermost loop around it, so break inside an if inside a foreach stops the foreach. To skip only the current element, use continue. In nested loops, break 2 leaves two loops at once and continue 2 moves on to the next pass of the outer loop.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground