Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

foreach() With All The Same Keys

<?php

function myGenerator() {
    yield 0 => 1;
    yield 0 => 2;
    yield 0 => 3;
}

foreach (myGenerator() as $key => $value) {
    echo $key . PHP_EOL;
}

// Output:
// 0
// 0
// 0

?>

It is possible for a foreach() loop to produce multiple times the same key. To do so, avoid using arrays, which enforce the unique key.

One need to use a generator or a Traversable class, where the same key is always yielded.

See Also

PHP Features

Last updated: 10 September 2026