Bug #79459 [Opn->Nab]: foreach twice with(out) assignment error

From: Date: Wed, 08 Apr 2020 15:03:25 +0000
Subject: Bug #79459 [Opn->Nab]: foreach twice with(out) assignment error
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-226488@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=79459&edit=1 ID: 79459 Updated by: sjon@php.net Reported by: fauvel dot marc at free dot fr Summary: foreach twice with(out) assignment error -Status: Open +Status: Not a bug Type: Bug Package: *General Issues Operating System: Docker (official) PHP Version: 7.4.4 Block user comment: N Private report: N New Comment: Sorry, but your problem does not imply a bug in PHP itself. For a list of more appropriate places to ask for help using PHP, please visit http://www.php.net/support.php as this bug system is not the appropriate forum for asking support questions. Due to the volume of reports we can not explain in detail here why your report is not a bug. The support channels will be able to provide an explanation for you. Thank you for your interest in PHP. you should unset($b); between the two foreach loops if you want to remove the reference Previous Comments: ------------------------------------------------------------------------ [2020-04-08 14:57:59] bugreports at gmail dot com after the first loop $b is still a reference to the last item in $a, that's why you should avoid references unlinke there are damned good reasons and most of the time there aren't sounds like a tpyical "i didn't understand teh side effects of references" case ------------------------------------------------------------------------ [2020-04-08 14:52:21] fauvel dot marc at free dot fr fix typo on os ------------------------------------------------------------------------ [2020-04-08 14:50:46] fauvel dot marc at free dot fr Description: ------------ In the test script, I expect $a to finish with [1, 1, 1] but the actual result is [1, 1, 2] Now if i change in the second loop $b with $c, the problem solve itself. I think $b already exist so the second foreach dont recreate it. And the second problem is that foreach dont iterate the second time ( [2, 2, 2] would have be a strange result but acceptable) Test script: --------------- <?php $a = [0, 0, 0]; foreach($a as &$b) $b = 1; foreach($a as $b) $b = 2; print_r($a); ?> Expected result: ---------------- $a = [1, 1, 1]; Actual result: -------------- $a = [1, 1, 2]; ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=79459&edit=1

« previous php.bugs (#226488) next »