Bug #75652 [Com]: foreach strange error
| From: | danack@php.net | Date: | Fri, 08 Dec 2017 10:41:53 +0000 |
| Subject: | Bug #75652 [Com]: foreach strange error | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-213010@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=75652&edit=1
ID: 75652
Comment by: danack@php.net
Reported by: nikolay at rockstonedev dot com
Summary: foreach strange error
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: Gentoo
PHP Version: 7.2.0
Block user comment: N
Private report: N
New Comment:
There's an explanation of what is happening on this bug https://bugs.php.net/bug.php?id=74751
tl:dr, the reference carries over from one foreach to the next. Re-using variable names when they
have been used as a reference, without having an explicit 'unset' is inherently
'surprising'.
Previous Comments:
------------------------------------------------------------------------
[2017-12-08 10:38:32] daverandom@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
After the first loop, $value remains a reference to the last element in the array. The second loop
assigns each element in the array to the last element of the array.
On the last iteration of the second loop, $value remains a reference to the previous element (which
is now 4 because of the increment in the first loop).
------------------------------------------------------------------------
[2017-12-08 10:32:46] nikolay at rockstonedev dot com
Description:
------------
Using foreach with & for getting address of variable changes last element of array in next
foreach
Test script:
---------------
<?php
$values = array('a' => 1, 'b' => 2, 'c' => 3, 'd'
=> 4);
$sum = 0;
foreach ($values as &$value)
$value++;
foreach ($values as $value)
$sum += $value;
print_r($values);
?>
Expected result:
----------------
Array
(
[a] => 2
[b] => 3
[c] => 4
[d] => 5
)
Actual result:
--------------
Array
(
[a] => 2
[b] => 3
[c] => 4
[d] => 4
)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=75652&edit=1