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 Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
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

Pull Requests

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-2024 The PHP Group
All rights reserved.
Last updated: Sun Oct 13 04:01:26 2024 UTC