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
 [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-2018 The PHP Group
All rights reserved.
Last updated: Sat Nov 17 03:01:25 2018 UTC