Bug #76931 [Nab]: foreach by reference copies last array element from second-last

From: Date: Mon, 24 Sep 2018 21:57:17 +0000
Subject: Bug #76931 [Nab]: foreach by reference copies last array element from second-last
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-217228@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=76931&edit=1 ID: 76931 User updated by: kellnerdenes at gmail dot com Reported by: kellnerdenes at gmail dot com Summary: foreach by reference copies last array element from second-last Status: Not a bug Type: Bug Package: *General Issues Operating System: Win64 PHP Version: 7.1.22 Block user comment: N Private report: N New Comment: Sure, you're right, it's somewhat expectable that the reference remains in $x from the first foreach; but the second foreach should create a new variable as $x, not reuse it. I can't see why it would keep it. Previous Comments: ------------------------------------------------------------------------ [2018-09-24 21:50:27] spam2 at rhsoft dot net to be clear: foreach($a as &$x); unset($x); foreach($a as $x); just don't use references until you understand the side-effects and are really sure you ebenfit from it which is motsly not true given the copy-on-write nature of PHP ------------------------------------------------------------------------ [2018-09-24 21:48:28] spam2 at rhsoft dot net man uset() ------------------------------------------------------------------------ [2018-09-24 21:26:25] requinix@php.net http://php.net/manual/en/control-structures.foreach.php Big red warning. Should be hard to miss. ------------------------------------------------------------------------ [2018-09-24 21:20:21] kellnerdenes at gmail dot com Description: ------------ When looping along an array twice, first by reference, then by just normal value, the last element gets affected (gets the value of the second-last). So while it should display "first second third fourth", it will give "first second third third" instead. Commenting any of the foreaches or changing their order makes the problem disappear. I've seen similar reports but I think this one is clearly a bug while others seem to be unsure. Test script: --------------- $a = explode("\n","first\nsecond\nthird\nfourth"); foreach($a as &$x); foreach($a as $x); print_r($a); Expected result: ---------------- Array ( [0] => first [1] => second [2] => third [3] => fourth ) Actual result: -------------- Array ( [0] => first [1] => second [2] => third [3] => third ) ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=76931&edit=1

« previous php.bugs (#217228) next »