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
 [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: Wed Apr 24 10:01:31 2024 UTC