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: 14 July 2026