php.net |  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
 [2021-08-11 12:37 UTC] 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<

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-08-11 12:40 UTC] cmb@php.net
-Status: Open +Status: Not a bug -Assigned To: +Assigned To: cmb
 [2021-08-11 12:40 UTC] 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: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: Sat Apr 27 10:01:29 2024 UTC