|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Dec 01 01:00:01 2025 UTC |
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.