php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #66256 Generator::current() does not support return value by reference
Submitted: 2013-12-10 17:33 UTC Modified: 2015-04-14 15:11 UTC
Votes:5
Avg. Score:3.6 ± 1.4
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: edmond at inbox dot ru Assigned: nikic (profile)
Status: Wont fix Package: Scripting Engine problem
PHP Version: 5.5Git-2013-12-10 (snap) OS: Windows 7 64
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2013-12-10 17:33 UTC] edmond at inbox dot ru
Description:
------------
Generator::current() does not support return value by reference.
I note foreach operator works fine with yield result which passed by reference.

The code below works normal:

function &my_test(&$array)
{
    foreach($array as $key => &$value)
    {
        yield $key => $value;
    }
}

$array = ['x1' => 1,'x2' => 2, 'x3' => 3,'x4' => 4];

foreach(my_test($array) as $key => &$value)
{
    $value = $value + 10;
    echo "$key => $value\n";
}

print_r($array);

But when I use Generator::current() I get a different result.

On the other hand Generator::current() does not have to return value by reference. But there must be another way to do it.


Test script:
---------------
function &my_test(&$array)
{
    foreach($array as $key => &$value)
    {
        yield $key => $value;
    }
}

$array          = ['x1' => 1,'x2' => 2, 'x3' => 3,'x4' => 4];

$generator      = my_test($array);

while($generator->valid())
{
    $value      = $generator->current();
    $key        = $generator->key();

    $value      = $value + 10;

    echo "$key => $value\n";

    $generator->next();
}

print_r($array);

Expected result:
----------------
x1 => 11
x2 => 12
x3 => 13
x4 => 14
Array
(
    [x1] => 11
    [x2] => 12
    [x3] => 13
    [x4] => 14
)

Actual result:
--------------
x1 => 11
x2 => 12
x3 => 13
x4 => 14
Array
(
    [x1] => 1
    [x2] => 2
    [x3] => 3
    [x4] => 4
)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-12-11 14:36 UTC] felipe@php.net
-Status: Open +Status: Assigned -Assigned To: +Assigned To: nikic
 [2014-08-08 11:04 UTC] elliot at aanet dot com dot au
I assume this was never fixed.
Is there any known workaround?
 [2015-04-14 15:11 UTC] nikic@php.net
-Status: Assigned +Status: No Feedback
 [2015-04-14 15:11 UTC] nikic@php.net
Marking this as Won't Fix, as I don't this is a useful feature and it would add a performance overhead for all usages. ArrayIterator, which is the only other iterator that supports by-ref iteration in foreach (as far as I know), also has ::current() returning by-value.
 [2015-04-14 15:11 UTC] nikic@php.net
-Status: No Feedback +Status: Wont fix
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 13:01:29 2024 UTC