php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49347 iterating through an array plus creating a refererence to the current element
Submitted: 2009-08-24 15:44 UTC Modified: 2009-08-26 13:01 UTC
From: zoli at lippai dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.3.0 OS: OS X 10.5.8
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: zoli at lippai dot net
New email:
PHP Version: OS:

 

 [2009-08-24 15:44 UTC] zoli at lippai dot net
Description:
------------
When I iterate through an array with "for" and create a reference to the current element inside the for, then the last element of the array will be a reference to the previous element.
If I unset the reference variable at the end of every cycle, then it works fine.

Reproduce code:
---------------
<?php
$list = array(
	array('id' => 1),
	array('id' => 2)
);
for($i = 0; $i < count($list); $i++) {
	$item = &$list[$i];
	$item['someValue'] = 'x';
}
foreach($list as $item)
{
	var_dump($item);
}

Expected result:
----------------
array(2) {
  ["id"]=>
  int(1)
  ["someValue"]=>
  string(1) "x"
}
array(2) {
  ["id"]=>
  int(2)
  ["someValue"]=>
  string(1) "x"
}


Actual result:
--------------
array(2) {
  ["id"]=>
  int(1)
  ["someValue"]=>
  string(1) "x"
}
array(2) {
  ["id"]=>
  int(1)
  ["someValue"]=>
  string(1) "x"
}

(Please note the second elements id, which is 1 instead of 2)

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-08-24 18:14 UTC] sjoerd@php.net
The variable $list has the expected value after the for loop. You can show this by doing print_r($list). However, the $item in the first for loop seems to interfere with the $item in the second foreach loop.
 [2009-08-24 20:36 UTC] jani@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php


 [2009-08-26 13:01 UTC] zoli at lippai dot net
Here is an other example:

$list = array(
	array('id' => 1),
	array('id' => 2)
);
for($i = 0; $i < count($list); $i++) {
	$item = &$list[$i];
	$item['someValue'] = 'x';
}
var_dump($list);

after that the value of $list is:

array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["someValue"]=>
    string(1) "x"
  }
  [1]=>
  &array(2) {
    ["id"]=>
    int(2)
    ["someValue"]=>
    string(1) "x"
  }

The second element has a & in front of it, I think this is causing the 
problem.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 30 18:00:02 2025 UTC