php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #40654 reference causes foreach to fail proper iteration
Submitted: 2007-02-27 04:44 UTC Modified: 2007-02-27 12:30 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: saeven at saeven dot net Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.1 OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: saeven at saeven dot net
New email:
PHP Version: OS:

 

 [2007-02-27 04:44 UTC] saeven at saeven dot net
Description:
------------
Using a reference to build an array, later causes foreach to fail when reusing the reference variable name.

The bug is solved by adding unset( $element); before block B, but this shouldn't be necessary.

Reproduce code:
---------------
// Block A - Build the Array
$a = array( 2 => array( "value" => "a" ), 
			4 => array( "value" => "b" ),
			6 => array( "value" => "c" ) );
			
$b = array( "orange", "blue", "green" );

foreach( $a as $id => &$element ){
	$extra = array();
	
	foreach( $b as $color )
		array_push( $extra, $color );
		
	$element += array( 'extra' => $extra );
}

// Block B - Iterate through
foreach( $a as $element )
	echo $element["value"].' ';


Expected result:
----------------
a b c

Actual result:
--------------
a b b

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-02-27 05:00 UTC] same at saeven dot net
I'd add that print_r properly displays the constructed array, which contradicts what foreach displays (which is why I thought this required filing).
 [2007-02-27 12:30 UTC] tony2001@php.net
Duplicate of bug #29992.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Apr 28 08:01:28 2025 UTC