php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49752 reference maintained across different loops
Submitted: 2009-10-02 18:24 UTC Modified: 2009-10-03 00:37 UTC
From: stevew at amainhobbies dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.2.11 OS: Win32 / Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: stevew at amainhobbies dot com
New email:
PHP Version: OS:

 

 [2009-10-02 18:24 UTC] stevew at amainhobbies dot com
Description:
------------
I don't expect the $total in the second foreach to still be a reference to the last item from the previous foreach.



Reproduce code:
---------------
<?php
  $totals = array(array('class' => 'Foo', 'value' => '1'),
                  array('class' => 'Test', 'value' => '2'),
                  array('class' => 'Bar', 'value' => '3'));

   foreach ($totals as &$total) {
   switch ($total['class']) {
     case 'Test':
        $total['value'] *= 2;
        break;
      default:
        break;
    }
  }

  foreach ($totals as $total) {
    echo $total['class'] . ' : ' . $total['value'] . "\n";
  }
?>


Expected result:
----------------
Foo : 1
Test : 4
Bar : 3


Actual result:
--------------
Foo : 1
Test : 4
Test : 4


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-10-02 21:31 UTC] fa@php.net
This has been like this since at least 5.1.6 (just tested) and also in 5.3.0.
 [2009-10-03 00:37 UTC] rasmus@php.net
There is no reason the reference would be broken here.  This is expected.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Sep 17 07:00:01 2025 UTC