php.net |  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
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:
MUST BE VALID
Solve the problem:
27 + 31 = ?
Subscribe to this entry?

 
 [2012-06-05 15:59 UTC] a1283465 at jnxjn dot com
Description:
------------
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


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-06-05 22:43 UTC] nikic@php.net
Duplicate of https://bugs.php.net/bug.php?id=60024 and a few other bugs linked in there.
 [2012-06-05 22:43 UTC] nikic@php.net
-Status: Open +Status: Duplicate
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 02:01:30 2024 UTC