php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79629 Generator duplicating first elements in 7.4.6
Submitted: 2020-05-25 09:47 UTC Modified: 2020-05-25 09:50 UTC
From: thiago dot barcala at gmail dot com Assigned:
Status: Duplicate Package: Unknown/Other Function
PHP Version: 7.4.6 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: thiago dot barcala at gmail dot com
New email:
PHP Version: OS:

 

 [2020-05-25 09:47 UTC] thiago dot barcala at gmail dot com
Description:
------------
It seems like the fix for https://bugs.php.net/bug.php?id=78434 changed the behavior of generators.

In version 7.4.5 the attached test script gives the expected output, but on 7.4.6, iterating over the generator yields the fist elements two times.

If I replace:
```
    if ($termination) {
        yield from $iterable;
        return;
    }
```

... with:
```
    if ($termination) {
        foreach ($iterable as $item) {
            yield $item;
        }
        return;
    }
```
It works as expected in both PHP versions.

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

function flatten(iterable $iterable, $termination = false) {
    if ($termination) {
        yield from $iterable;
        return;
    }

    foreach ($iterable as $item) {
        yield from flatten($item, true);
    }
}

function testGenerator() {
    yield [1, 2];
}

echo 'Dumping with iterator_to_array:' . PHP_EOL;
var_dump(iterator_to_array(flatten(testGenerator())));

echo 'Echoing keys/elements with foreach:' . PHP_EOL;
foreach (flatten(testGenerator()) as $key => $item) {
    echo "key $key => value $item\n";
}


Expected result:
----------------
Dumping with iterator_to_array:
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
Echoing keys/elements with foreach:
key 0 => value 1
key 1 => value 2

Actual result:
--------------
Dumping with iterator_to_array:
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
Echoing keys/elements with foreach:
key 0 => value 1
key 0 => value 1
key 1 => value 2

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-05-25 09:50 UTC] requinix@php.net
-Status: Open +Status: Duplicate
 [2020-05-25 09:50 UTC] requinix@php.net
Duplicate of bug #79600
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Mon Nov 29 21:03:45 2021 UTC