php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70510 Variables defined by a cycle are not isolated and cause side effects
Submitted: 2015-09-16 10:28 UTC Modified: 2015-09-16 17:56 UTC
From: mumu at seznam dot cz Assigned:
Status: Not a bug Package: Variables related
PHP Version: 7.0.0RC2 OS: Windows
Private report: No CVE-ID: None
 [2015-09-16 10:28 UTC] mumu at seznam dot cz
Description:
------------
The first cycle has $item defined by reference. The second by value. 

The $item keeps being a reference to the (last item of the) array even it is used as by value inside the second cycle.

As such, the two cycles are not properly isolated as would have been expected.

Test script:
---------------
<?php

$list = array(
    'a' => 'x',
    'b' => 'y',
    'c' => 'z',
);

foreach ($list as &$item) {
    $item .= $item;
}

foreach ($list as $key => $item) {
    echo $key . ': ' . $item . "\n";
}

?>

Expected result:
----------------
a: xx
b: yy
c: zz

Actual result:
--------------
a: xx
b: yy
c: yy

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-09-16 17:56 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2015-09-16 17:56 UTC] requinix@php.net
$item is still a reference to the last item after the first loop ends. When the second begins, it will overwrite $item with values from the array - dump out $list inside the loop and you'll see [c] change to 'xx' and 'yy'.

unste($item) after the first loop to destroy the reference.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 05:01:30 2024 UTC