php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #36240 foreach($arr as $k => &$v) corrupts array on second iteration
Submitted: 2006-02-01 06:35 UTC Modified: 2006-02-01 09:19 UTC
From: dshadow at zort dot net Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.1.2 OS: Mac OS X
Private report: No CVE-ID: None
 [2006-02-01 06:35 UTC] dshadow at zort dot net
Description:
------------
After using foreach($arr as $k => &$v) to modify the $arr, 
iterating again using the same variable $v causes the array to 
be altered unexpectedly.

Adding an unset($v) between the two foreach loops, or using a 
different variable on the second foreach loop works around the 
problem.

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

$arr = array(
	'one' => 1,
	'two' => 2,
	'three' => 3,
);

foreach($arr as $k => &$v)
	if($v == 1)
		$v = 'meh';

print_r($arr);

foreach($arr as $k => $v)
	;

print_r($arr);


Expected result:
----------------
The code above should not cause the $arr to be modified by 
running the second foreach loop.

Actual result:
--------------
The code above outputs the following:

Array ( [one] => meh [two] => 2 [three] => 3 )
Array ( [one] => meh [two] => 2 [three] => 2 )


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-02-01 08:20 UTC] judas dot iscariote at gmail dot com
BOGUS.
read  bug 29992
 [2006-02-01 09:19 UTC] derick@php.net
Please do not submit the same bug more than once. An existing
bug report already describes this very problem. Even if you feel
that your issue is somewhat different, the resolution is likely
to be the same. 

Thank you for your interest in PHP.

Duplicate of bug #29992
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 17:01:30 2024 UTC