Edit report at https://bugs.php.net/bug.php?id=60450&edit=1
ID: 60450 Updated by: cataphr...@php.net Reported by: developer at elementica dot com Summary: Looping in a copy of an array using foreach by-reference change original array -Status: Open +Status: Bogus Type: Bug Package: Arrays related Operating System: Linux, Windows PHP Version: 5.3.8 Block user comment: N Private report: N New Comment: See http://nl.php.net/manual/en/language.references.whatdo.php#language.references.whatdo.assign near the end. The work-around is unsetting the $elem variable after the last iteration when iterating by reference. Previous Comments: ------------------------------------------------------------------------ [2011-12-06 10:05:23] developer at elementica dot com Description: ------------ On a standard installation of PHP 5.3.x on many OSs (including Linux and Windows) we: - set an array with at least two elements - loop it using foreach by-reference changing each element - create a copy of the array in another one using the "=" assignment - loop on the copy as before - we find the original array changed (usually or always: last element) Example code given. Documentation says "Array assignment always involves value copying. Use the reference operator to copy an array by reference." (http://php.net/manual/en/language.types.array.php). It seems a problem of "foreach" used with the "by-reference" syntax. Could be related to https://bugs.php.net/bug.php?id=8130 (subject appears to be the same, but here we have a foreach problem, while nothing is stated in #8130 about it). Test script: --------------- $array1 = array(0 => 'zero', 1 => 'one'); foreach ($array1 as &$elem) { $elem .= ' (1)'; }; // NOTE: if we use $array1[0] .= ' (1)'; $array1[1] .= ' (1)'; no problem arises $array2 = $array1; foreach ($array2 as &$elem) { $elem .= ' (2)'; }; // NOTE: if we use $array2[0] .= ' (1)'; $array2[1] .= ' (1)'; the problem is still here, so first foreach seems to be the point print_r ($array1); // BUG! EXPECTED: array(0 => 'zero (1)', 1 => 'one (1)'), OUTPUT: array(0 => 'zero (1)', 1 => 'one (1) (2)') Expected result: ---------------- Array ( [0] => zero (1) [1] => one (1) ) Actual result: -------------- Array ( [0] => zero (1) [1] => one (1) (2) ) ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=60450&edit=1