php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75652 foreach strange error
Submitted: 2017-12-08 10:32 UTC Modified: 2017-12-08 10:38 UTC
From: nikolay at rockstonedev dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.2.0 OS: Gentoo
Private report: No CVE-ID: None
 [2017-12-08 10:32 UTC] 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
)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-12-08 10:38 UTC] daverandom@php.net
-Status: Open +Status: Not a bug
 [2017-12-08 10:38 UTC] 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:41 UTC] danack@php.net
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'.
 [2017-12-08 10:43 UTC] daverandom@php.net
As a general rule, the best advice is not to use foreach by reference. If you have a legitimate case for doing so, best practice to avoid unexpected results is to do at least one of the following:

1) Do not re-use the iteration variable ($value in your code sample) again in the same scope. https://3v4l.org/b6CN0
2) Break the reference chain explicitly by calling unset($value) as soon as you have finished your use for the reference - in your sample code this would be immediately after the first loop. https://3v4l.org/nldtj
 [2017-12-11 00:28 UTC] a at b dot c dot de
See also the big red WARNING on the foreach manual page
www.php.net/control-structures.foreach
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 17:01:30 2024 UTC