3v4l.org

run code in 300+ PHP versions simultaneously
<?php function chained(iterable ...$input): Generator { foreach ($input as $iterable) { yield from $iterable; } } echo "The \"chained\" iterable contains all elements, using a generator: "; foreach(chained( [1,2,3], [4,5], ) as $item){ echo "$item "; } echo "\n\n"; echo "However, when it comes to converting the generator to array, there is a caveat:\n"; $numbers = chained( [1,2,3], [4,5], ); print_r( iterator_to_array($numbers) ); echo "\n"; echo "The issue is caused by overlapping keys. See how they appear in the sequence:\n"; foreach(chained( [1,2,3], [4,5], ) as $key => $item){ echo "[$key] => $item\n"; } echo "\n\n"; echo "The issue is not present when the keys do not overlap:\n"; $numbers = chained( [1,2,3], [10 => 4,5], ); print_r( iterator_to_array($numbers) );

preferences:
24.5 ms | 405 KiB | 5 Q