Bug #75652 [Opn->Nab]: foreach strange error
| From: | daverandom@php.net | Date: | Fri, 08 Dec 2017 10:38:36 +0000 |
| Subject: | Bug #75652 [Opn->Nab]: foreach strange error | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-213009@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
Updated by: daverandom@php.net
Reported by: nikolay at rockstonedev dot com
Summary: foreach strange error
-Status: Open
+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:
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).
Previous Comments:
------------------------------------------------------------------------
[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