|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81350 foreach returns unexpected result
Submitted: 2021-08-11 12:37 UTC Modified: 2021-08-11 12:46 UTC
From: wilhelm at blueend dot com Assigned: cmb (profile)
Status: Not a bug Package: Variables related
PHP Version: 7.4.22 OS: CentOS
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
12 + 39 = ?
Subscribe to this entry?

 [2021-08-11 12:37 UTC] wilhelm at blueend dot com
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){
foreach ($t as $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<


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2021-08-11 12:40 UTC]
-Status: Open +Status: Not a bug -Assigned To: +Assigned To: cmb
 [2021-08-11 12:40 UTC]
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at and the instructions on how to report
a bug at

Especially see the big warning on
 [2021-08-11 12:40 UTC] rtrtrtrtrt at dfdfdfdf dot dfd
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
 [2021-08-11 12:46 UTC] wilhelm at blueend dot com
Even after 15 years of PHP you learn new things :-) Thank you for the reference to the warning.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Feb 26 07:01:28 2024 UTC