3v4l.org

run code in 300+ PHP versions simultaneously
<?php function merged(iterable ...$input): Generator { foreach ($input as $iterable) { yield from $iterable; } } echo "The \"merged\" elements using a generator: "; foreach(merged( [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 = merged( [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(merged( [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 = merged( [1,2,3], [10 => 4,5], ); print_r( iterator_to_array($numbers) );
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
The "merged" elements using a generator: 1 2 3 4 5 However, when it comes to converting the generator to array, there is a caveat: Array ( [0] => 4 [1] => 5 [2] => 3 ) The issue is caused by overlapping keys. See how they appear in the sequence: [0] => 1 [1] => 2 [2] => 3 [0] => 4 [1] => 5 The issue is not present when the keys do not overlap: Array ( [0] => 1 [1] => 2 [2] => 3 [10] => 4 [11] => 5 )

preferences:
55.41 ms | 403 KiB | 62 Q