Bug #77397 [Opn->Nab]: Reference variable in foreach

[email protected] Wed, 02 Jan 2019 10:11:58 +0000
Newsgroups php.standards
Message-ID <[email protected]>
Edit report at https://bugs.php.net/bug.php?id=77397&edit=1

 ID:                 77397
 Updated by:         [email protected]
 Reported by:        shranet at gmail dot com
 Summary:            Reference variable in foreach
-Status:             Open
+Status:             Not a bug
 Type:               Bug
 Package:            PHP Language Specification
 Operating System:   MacOS
 PHP Version:        7.2.13
 Block user comment: N
 Private report:     N

 New Comment:

Please see the red "Warning" box on http://php.net/manual/en/control-structures.foreach.php, which explains this behavior. You can avoid it by writing unset($v) after the first foreach loop.


Previous Comments:
------------------------------------------------------------------------
[2019-01-02 10:06:28] shranet at gmail dot com

Description:
------------
When using same variable with reference and without reference in foreach works incorrectly.

Test script:
---------------
$data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

foreach($data as $k => &$v) {
    rsort($v);
}

foreach($data as $k => $v) {
    print_r($v);
}

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

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



------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=77397&edit=1