Bug #81350 [Com]: foreach returns unexpected result
| From: | rtrtrtrtrt at dfdfdfdf dot dfd | Date: | Wed, 11 Aug 2021 12:40:47 +0000 |
| Subject: | Bug #81350 [Com]: foreach returns unexpected result | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-235763@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=81350&edit=1
ID: 81350
Comment by: rtrtrtrtrt at dfdfdfdf dot dfd
Reported by: wilhelm at blueend dot com
Summary: foreach returns unexpected result
Status: Not a bug
Type: Bug
Package: Variables related
Operating System: CentOS
PHP Version: 7.4.22
Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
fix your broken expectation!
after the first loop it is still a reference unless you use unset($t) between both loops -
don't use references is the solution because you gain nothing but troubles in a COW language
Previous Comments:
------------------------------------------------------------------------
[2021-08-11 12:40:45] cmb@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php
Especially see the big warning on
<https://www.php.net/manual/en/control-structures.foreach.php>.
------------------------------------------------------------------------
[2021-08-11 12:37:03] wilhelm at blueend dot com
Description:
------------
If you have two foreach loops based on the same array and the first loop uses the variable as
reference the second loop produces an unexpected result if the variable name for the value stays the
same.
Test script:
---------------
$t = [1,2,3];
foreach ($t as &$testVar){
print_r($testVar);
}
foreach ($t as $testVar){
print_r($testVar);
}
Expected result:
----------------
I would expect the same output as if I would have used the non reference variant in the first place.
I would expect
=> (Loop 1) 1,2,3
=> (Loop 2) 1,2,>3<
Actual result:
--------------
I get
=> (Loop 1) 1,2,3
=> (Loop 2) 1,2,>2<
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81350&edit=1