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
 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 08:01:27 2024 UTC