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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
38 - 17 = ?
Subscribe to this entry?

 
 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Tue Apr 30 07:01:28 2024 UTC