|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2005-05-28 16:30 UTC] tomas_matousek at hotmail dot com
[2005-06-03 21:22 UTC] sniper@php.net
[2005-06-03 23:39 UTC] tomas_matousek at hotmail dot com
[2005-06-06 10:15 UTC] sniper@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 00:00:01 2025 UTC |
Description: ------------ The behavior of foreach statment with reference value is not imho right if the array gets modified during iteration. See the code I've pasted here. If the array is written to (either by unset or by a write operation) during iteration, the effect of & is canceled, i.e. the values are not modified since the write operation. This seems to me as bug because it is inconsistent with the "definition" of foreach which should say that foreach($a as $k => $v) {} is (more or less) equivalent to $copy_of_a = $a; while(next($copy_of_a)) { $k = key($copy_of_a); $v = $copy_of_a[$k]; } With the &, one can deduce the following "definition": foreach($a as $k =>& $v) { } is equivalent to $copy_of_a = $a; while(next($copy_of_a)) { $k = key($copy_of_a); $v =& $a[$k]; } Using =& operator, a new value should be added if it has been unset in the original array. Reproduce code: --------------- $a = array(0,1,2,3,4,5,6,7,8); $i = 0; foreach ($a as $k =>& $v) { $v+=100; if ($i++==2) { unset($a[5]); } } var_dump($a); Expected result: ---------------- array(8) { [0]=> int(100) [1]=> int(101) [2]=> int(102) [3]=> int(3) // modification of values stops here [4]=> int(4) [6]=> int(6) [7]=> int(7) [8]=> int(8) } Actual result: -------------- array(8) { [0]=> int(100) [1]=> int(101) [2]=> int(102) [3]=> int(103) [4]=> int(104) [6]=> int(106) [7]=> int(107) [8]=> int(108) [5]=> // note: the new value should be added here int(100) }