|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #62233 foreach destroys arrays
Submitted: 2012-06-05 15:59 UTC Modified: 2012-06-05 22:43 UTC
From: a1283465 at jnxjn dot com Assigned:
Status: Duplicate Package: Arrays related
PHP Version: 5.3.13 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: a1283465 at jnxjn dot com
New email:
PHP Version: OS:


 [2012-06-05 15:59 UTC] a1283465 at jnxjn dot com
See script outputs below.

Please note that the array is already broken after the first foreach run because the last array element is now a pointer.

Workaround for the second foreach loop:
Do a unset($val) between the two foreach loops.

Test script:
$a = array(1,2,3);
var_dump($a); // array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
foreach ($a as &$val) { } // Now the array is broken
var_dump($a); // array(3) { [0]=> int(1) [1]=> int(2) [2]=> &int(3) }
foreach ($a as $val) { } // Now the array is destroyed
var_dump($a); // array(3) { [0]=> int(1) [1]=> int(2) [2]=> &int(2) }
echo $a[2]; // Output: 2, Expected: 3


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2012-06-05 22:43 UTC]
Duplicate of and a few other bugs linked in there.
 [2012-06-05 22:43 UTC]
-Status: Open +Status: Duplicate
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Jul 25 17:01:27 2024 UTC