php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45385 unset in foreach breaks recrusion
Submitted: 2008-06-28 13:08 UTC Modified: 2008-06-29 17:18 UTC
From: espaiz at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.6 OS: Debian 4.0.3
Private report: No CVE-ID: None
 [2008-06-28 13:08 UTC] espaiz at gmail dot com
Description:
------------
Made a simple recrusion function, sorting id by parentid, unsetting sorted values to shorten time of next recrusions. Unsetting inside foreach with deep arrays does work(!), but with simple array unset somehow stops the recrusion (first cicle will never finish its loop, the last loop will be made by latest child).

Tested with PHP 5.2.6 on Debian-40r3-amd64 and Windows Vista 32


Reproduce code:
---------------
<?php
function recrusion($array, $return, $pid=0, $level=0){
	foreach($array as $id=>$parent){
		if( $parent===$pid ){
			$return[$id]= $level;
			unset($array[$id]); /* remove this to get correct results */
			recrusion(&$array, &$return, $id, $level+1);
		}
	}
}
$return= array();
$array= array(1=>0,2=>1,3=>2,4=>3,5=>2,6=>2,7=>6,8=>6,9=>0,10=>0);
recrusion($array, &$return);
var_dump( $return );
?>

Expected result:
----------------
array(10) { [1]=> int(0) [2]=> int(1) [3]=> int(2) [4]=> int(3) [5]=> int(2) [6]=> int(2) [7]=> int(3) [8]=> int(3) [9]=> int(0) [10]=> int(0) }

Actual result:
--------------
array(6) { [1]=> int(0) [2]=> int(1) [3]=> int(2) [4]=> int(3) [9]=> int(0) [10]=> int(0) } 

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-06-29 17:18 UTC] colder@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

php.net/foreach : "Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself."

$array = array(0,1,2);
$dummy =&$array;
foreach ($array as $k=>$v) {
    unset($array[1]);
    echo "$k:$v\n";
}

// 0:0
// 2:2

in your case, the array is referenced, so the unset will unset elements in the "parent" array which will affect the foreach of the parent call as well.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 09:01:26 2024 UTC