|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2021-05-24 00:20 UTC] a3ron223 at gmail dot com
[2021-07-20 09:48 UTC] cmb@php.net
-Summary: Using a reference as iterator variable turns the
whole array into a reference
+Summary: foreach by-val vs. by-ref traversal unclear
-Status: Open
+Status: Verified
[2021-07-20 09:48 UTC] cmb@php.net
[2022-11-26 13:26 UTC] plumbingadvice24 at gmail dot com
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 20:00:01 2025 UTC |
Description: ------------ I'm not sure whether this is a bug or a documentation bug. I'd consider it a bug but given the promise of backwards compatibility it's unlikely to be fixed. If the iterator variable in a foreach is a reference, then the whole array becomes a reference and it is no longer safe to append to the array. This is true even when the iterator variable is not actually used anywhere. At least this behavior should be documented. The documentation currently says: > In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. It says nothing about the array itself, only about the array values, reenforcing the wrong impression that it is still safe to add or remove array elements. Test script: --------------- $arr = ['a','b','c']; foreach ($arr as &$dummy) { $arr []= 'foo'; } var_dump($arr); Expected result: ---------------- array(6) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(3) "foo" [4]=> string(3) "foo" [5]=> string(3) "foo" } Actual result: -------------- Fatal error: Allowed memory size of [...] bytes exhausted