Bug #74020 [Opn->Ver]: Foreach-by-reference + assignment may recreate unexpected key references

From: Date: Tue, 31 Jan 2017 08:57:39 +0000
Subject: Bug #74020 [Opn->Ver]: Foreach-by-reference + assignment may recreate unexpected key references
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-207058@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=74020&edit=1 ID: 74020 Updated by: requinix@php.net Reported by: icarpenter at leadid dot com -Summary: Foreach-by-reference may create unexpected key references +Summary: Foreach-by-reference + assignment may recreate unexpected key references -Status: Open +Status: Verified Type: Bug -Package: Arrays related +Package: Scripting Engine problem PHP Version: 7.0.15 Block user comment: N Private report: N New Comment: Note that var_dump on the array will show references. The first one looks like a bug as the reference was (supposedly) destroyed, however it comes back with the foo_copy=foo assignment. https://3v4l.org/DgJFP#v700 The second is not because $item is still a reference after the loop and when $mockCopy copies $mock it gets foo as a copy *of the reference*. https://3v4l.org/nrpE5 Adding unset($item) is the recommended solution. http://php.net/foreach Previous Comments: ------------------------------------------------------------------------ [2017-01-31 03:08:04] icarpenter at leadid dot com Description: ------------ After a foreach-by-reference, an array may create references to keys if you create a copy of the original variable (either directly or indirectly via foreach) and then on that new variable, create a copy of a key to another key. The original key in that variable will then become a reference to the same key in the original array. In PHP 5.6 and 7.1, this can be avoided by either having the foreach run in a different scope, or unsetting the reference variable after the loop. PHP 7.0 exhibits this behavior regardless. Test script: --------------- https://3v4l.org/mHX7B (Triggers the bug in PHP 7.0) https://3v4l.org/VLuhn (Triggers the bug in PHP 5.6, 7.0, and 7.1) Expected result: ---------------- string(3) "foo" Actual result: -------------- string(3) "bar" ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=74020&edit=1

« previous php.bugs (#207058) next »