php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77397 Reference variable in foreach
Submitted: 2019-01-02 10:06 UTC Modified: 2019-01-02 10:12 UTC
From: shranet at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.2.13 OS: MacOS
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: shranet at gmail dot com
New email:
PHP Version: OS:

 

 [2019-01-02 10:06 UTC] 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
)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-01-02 10:11 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2019-01-02 10:11 UTC] nikic@php.net
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.
 [2019-01-02 10:12 UTC] nikic@php.net
-Package: PHP Language Specification +Package: Scripting Engine problem
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 23:01:29 2024 UTC