php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72518 iterator_to_array() misses values from generator using yield from
Submitted: 2016-06-29 20:36 UTC Modified: 2016-06-30 00:27 UTC
From: trowski@php.net Assigned:
Status: Not a bug Package: SPL related
PHP Version: 7.0.8 OS: OS X
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: trowski@php.net
New email:
PHP Version: OS:

 

 [2016-06-29 20:36 UTC] trowski@php.net
Description:
------------
iterator_to_array() does not add all values yielded from a generator if yield from is used in the generator.

Test script:
---------------
<?php

function gen1() {
    yield 1;
    yield from gen2();
    yield 5;
}

function gen2() {
    yield 2;
    yield 3;
    yield 4;
}

print_r(iterator_to_array(gen1(), true));

$result = [];

foreach (gen1() as $yielded) {
    $result[] = $yielded;
}

print_r($result);


Expected result:
----------------
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Actual result:
--------------
Array
(
    [0] => 2
    [1] => 5
    [2] => 4
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-29 20:50 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2016-06-29 20:50 UTC] nikic@php.net
Your iterator has duplicate keys. Use iterator_to_array() with $preserve_keys=false.
 [2016-06-29 21:06 UTC] trowski@php.net
Totally forgot that keys reset in the new generator. Sorry for the noise.
 [2016-06-30 00:27 UTC] bwoebi@php.net
For the record, I've added a note to the documentation:
http://svn.php.net/viewvc?view=revision&revision=339531

Perhaps the world is more aware of this then...
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Mar 16 08:01:28 2025 UTC