#42236 [Opn->Fbk]: unwanted array reset within recursive call

From: Date: Sat, 11 Aug 2007 11:58:18 +0000
Subject: #42236 [Opn->Fbk]: unwanted array reset within recursive call
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-115967@lists.php.net to get a copy of this message
 ID:               42236
 Updated by:       jani@php.net
 Reported By:      remy215 at laposte dot net
-Status:           Open
+Status:           Feedback
 Bug Type:         Arrays related
 Operating System: debian
 PHP Version:      5.2.4RC1
 New Comment:

Please try using this CVS snapshot:

  http://snaps.php.net/php5.2-latest.tar.gz
 
For Windows (zip):
 
  http://snaps.php.net/win32/php5.2-win32-latest.zip

For Windows (installer):

  http://snaps.php.net/win32/php5.2-win32-installer-latest.msi




Previous Comments:
------------------------------------------------------------------------

[2007-08-07 17:21:17] remy215 at laposte dot net

Description:
------------
I have an array of nested arrays (ie. each id can have nested
children). The function returns the parent of the provided id but end in
an infinite loop when the id does not exists !
Parent array at the top of the hierarchy seems to undergo an unwanted
reset();


Reproduce code:
---------------
<?php
$array=array('a0'=>array('a1'=>array('a2'=>array(),'b2'=>array()),'b1'=>array()),'b0'=>array());
$searched=array(); // to avoid infinite loop
function getParent($id,$_subtree=null) {
	if(!$_subtree) { // if first call
		global $array;
		$_subtree=$array; // entire tree
	}
	global $searched; // to avoid infinite loop
	$found_parent=null;
	foreach($_subtree as $parent=>$children) {
		if(in_array($parent,$searched)) { // if already looped => stop (ie.
infinite loop)
			die('Infinite loop: '.$parent);
		}
		array_push($searched,$parent); // to avoid infinite loop
		if(in_array($id,array_keys($children))) {
			$found_parent=$parent;
			break;
		} elseif($found_parent=getParent($id,$children)) {
			break;
		}
	}
	return $found_parent;
}
$search='a0';
echo 'parent of '.$search.' is: '.getParent($search);
?>

Expected result:
----------------
When you provide as argument a nested id, the function works ('b2'
returns 'a1').
When you provide a non-existing id, or one of the top parent ids ('a0'
or 'b0') the function should return null.

Actual result:
--------------
When you provide a non-existing id, or one of the top parent ids ('a0'
or 'b0') the function end up in an infinite loop.
Parent array at the top of the hierarchy seems to undergo an unwanted
reset();



------------------------------------------------------------------------


-- 
Edit this bug report at http://bugs.php.net/?id=42236&edit=1


Thread (10 messages)

« previous php.bugs (#115967) next »