diff --git a/src/functions.php b/src/functions.php index 17cd3f9..c453ff9 100644 --- a/src/functions.php +++ b/src/functions.php @@ -138,7 +138,10 @@ function split(ReadableStream $source, string $delimiter, ?Cancellation $cancell $split = \explode($delimiter, $buffer); $buffer = \array_pop($split); - yield from $split; + // Don't use yield from to avoid reusing the keys from $split + foreach ($split as $v) { + yield $v; + } } if ($buffer !== '') { diff --git a/test/SplitTest.php b/test/SplitTest.php index 128d64c..aeb3844 100644 --- a/test/SplitTest.php +++ b/test/SplitTest.php @@ -58,6 +58,20 @@ public function testMultiLineSlow(): void $this->check(["a", "bc", "\r", "\n\r\nef\r", "\n"], ["abc", "", "ef"]); } + public function testKey(): void + { + $stream = new ReadableIterableStream(Pipeline::fromIterable(["a|b|c", "|", "||d|e|f"])); + + $lines = []; + $expectedK = 0; + foreach (split($stream, '|') as $k => $line) { + $this->assertEquals($expectedK++, $k); + $lines[] = $line; + } + + self::assertSame(["a", "b", "c", "", "", "d", "e", "f"], $lines); + } + public function testCustomDelimiter(): void { $stream = new ReadableIterableStream(Pipeline::fromIterable(["a|b|c", "|", "||d|e|f"]));