php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #48561 foreach (var as &var construct overwrites last element of array
Submitted: 2009-06-15 18:16 UTC Modified: 2009-06-15 18:48 UTC
From: huf at nws dot hu Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.9 OS: linux 2.6
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: huf at nws dot hu
New email:
PHP Version: OS:

 

 [2009-06-15 18:16 UTC] huf at nws dot hu
Description:
------------
it looks like foreach (var as &val) syntax leaves a refecence alive after the last iteration. calling a subsequent foreach (var as val) (same variable being used to iterate, but not as a ref now), the reference from the first foreach is used to update the array...

Reproduce code:
---------------
<?php

$array = array(1, 2, 3);

foreach ($array as &$a) {
}
unset($a);
var_dump($array);
foreach ($array as $a) {
}

var_dump($array);


Expected result:
----------------
$array unchanged

Actual result:
--------------
$array changed.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-06-15 18:20 UTC] huf at nws dot hu
code to reproduce should be like:
<?php

$array = array(1, 2, 3);

foreach ($array as &$a) {
}

var_dump($array);
foreach ($array as $a) {
}

var_dump($array);
 [2009-06-15 18:48 UTC] jani@php.net
This has been reported as bug many times, it's also documented as being 
expected behaviour..RTFM.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 09 22:01:33 2025 UTC