|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2017-06-13 03:23 UTC] grmnpl46 at gmail dot com
Description:
------------
I'm altering only the first element of the array but the second one is somehow modified too - or the first one is displayed instead. This doesn't happen if at the second foreach I put also reference.
Test script:
---------------
$arr = [
[1, 2],
[3, 4]
];
foreach($arr as $i => &$a)
{
if($i === 0)
{
$a[0] = 6;
$a[1] = 7;
}
}
//correct result
print_r($arr);
foreach($arr as &$a)
print_r($a); //correct result
foreach($arr as $a)
print_r($a); //bug - displays same values twice
Expected result:
----------------
the 2 arrays should have different values.
Actual result:
--------------
the 2 arrays are identical
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 02:00:01 2025 UTC |
grmnpl - the explanation is that $a is still a variable which is a reference to the original array. Writing values into it, will write that value into the original array. Re-using the names of variables is usually a bad idea - particularly when using them with references. The behaviour you probably expected can be achieved by explicitly unsetting the $a variable: <?php $arr = [ [1, 2], [3, 4] ]; foreach($arr as $i => &$a) { if($i === 0) { $a[0] = 6; $a[1] = 7; } } //correct result print_r($arr); foreach($arr as &$a) print_r($a); //correct result unset($a); foreach($arr as $a) print_r($a); //bug - displays same values twice ?> This example shows that writing any variable into $a will alter the original array. <?php $arr = [ [1, 2], [3, 4] ]; foreach($arr as $i => &$a) { if($i === 0) { $a[0] = 6; $a[1] = 7; } } $a = "Wooo, magic"; foreach($arr as $b) { print_r($b); } ?>