Re: unset in foreach breaks recrusion

From: Date: Tue, 01 Jul 2008 15:13:17 +0000
Subject: Re: unset in foreach breaks recrusion
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-276175@lists.php.net to get a copy of this message
Jim, Read the first emails, your idea was my initial design, eg. $sorted= array(); recrusion($array, &$sorted); var_dump( $sorted ); It's not a "nice" solution due to a need to create variable before the call. Using my final function it will return sorted array into new variable eg $sorted = recur($array); It's easier to use and understand :) Thanks for your reply! On Tue, Jul 1, 2008 at 6:34 AM, Jim Lucas <lists@cmsws.com> wrote: > David Sky wrote: >> >> Hey, >> >> Can't use your example, as you check weather >> $sorted is empty, if it is -> run the foreach and return, >> but on next recursion when it's not empty - do nothing :) >> >> Though I found how to cut a few seconds (on very big array), >> removing the first if, and adding a $return=true to functions' >> parameters, and in future calls set it to false: >> >> function recur($array, &$sorted=array(), $pid=0, $level=0, $return=true) >> { >> foreach($array as $id=>$parent) >> { >> if($pid===$parent) >> { >> $sorted[$id]= $level; >> unset($array[$id]); >> if(in_array($id,$array)){ >> recur($array, &$sorted, $id, >> $level+1, false); >> } >> } >> } >> if($return){return $sorted;} >> } >> >> >> Well, I guess that's it, I'm sure I can think of >> another way to cut execution time, but, well, >> I don't have much time for it :) >> > > Why are you returning anything at all? I mean, you are making your function > call like this right? > > $dataOut = recur($dataIn, array(), 3); > > You are passing the second argument as a reference already, why not keep it > that way at the top level. Do this instead. > > recur($dataIn, $dataOut, 3); > > > Now, from what you function looks like, it would return $sorted through the > reference $dataOut. > > Then you can get rid of the extra if($return){return $sorted;} thing. Remove > the last argument from the function definition and you should now be a > little faster also. > >> >> Thanks all! >> >> David. >> >

« previous php.general (#276175) next »