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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
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

Pull Requests

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-2025 The PHP Group
All rights reserved.
Last updated: Sun Jul 13 02:01:32 2025 UTC