Re: [PHP] unset in foreach breaks recrusion



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.

.



Relevant Pages

  • Re: Why Lisp?
    ... Is that bit about the empty list being set-theoretic fals ... because the result is a circular reference. ... Those sentences are the parens around the empty set in the ...
    (comp.lang.lisp)
  • Re: Net::SFTP::Attributes
    ... no matter what I do dealing with $ref always seems to be ... "empty" is a term that applies to lists, arrays, and ... be called and given a reference to a hash with three keys: ...
    (comp.lang.perl.modules)
  • Re: C# Fundamentals Part 3: ReferenceEquals question
    ... |> take a look at the remark clausein the Framework reference guide. ... What is an "Empty ... String.Empty is a public static field of type String initialized ... empty string object. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: newbie trouble making array of instances
    ... an Empty instance is initialized." ... string x = string.Empty; ... "" is not reference equal to string.Empty. ... The old instance of str1 was replaced with a whole new instance. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: = operator between collections
    ... empty all elements from these collections. ... content of 'empty' is a reference to the collection, now also A and B point ... contain only the reference (= the position of the object in memory). ... Copying these variables also means copying the variable content, ...
    (microsoft.public.dotnet.languages.vb)