Bug #74751 [Com]: Array content changes but doesn't change
| From: | danack@php.net | Date: | Wed, 14 Jun 2017 16:05:34 +0000 |
| Subject: | Bug #74751 [Com]: Array content changes but doesn't change | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-209533@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=74751&edit=1
ID: 74751
Comment by: danack@php.net
Reported by: grmnpl46 at gmail dot com
Summary: Array content changes but doesn't change
Status: Not a bug
Type: Bug
Package: Arrays related
Operating System: any
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
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);
}
?>
Previous Comments:
------------------------------------------------------------------------
[2017-06-13 03:35:17] requinix@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
Please read the red warning on the foreach docs page.
------------------------------------------------------------------------
[2017-06-13 03:23:56] 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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=74751&edit=1