1

i have got the following recursive function:

private function myRecursiveFunction()
{
  $results = [];
  //stuff related to $results
  ...
  if(!$done){
     .....
     $this->myRecursiveFunction();
    }
  return $results;
}

when i do var_dump($results) inside function i got the all array results

but when i call the function from another one i will got only the first element in $results array.

public function myFunction()
{
 $results = $this->myRecursiveFunction();
}
2
  • 2
    I may be incorrect, but I thought recursive functions usually used a parameter? How can this be truly recursive if you use the same input (none) each time? Commented Feb 13, 2017 at 20:54
  • to be recursive the nth calls inside the function have to mudify the original $result, either by passing it in parameter by reference, or by retreiving the value, for exemple with $result[] = $this->myRecursiveFunction(); Commented Feb 13, 2017 at 20:57

1 Answer 1

4

I am not 100% sure what you wish to accomplish here, but recursive functions usually send their "workload" all the way to the innermost function, then the results are "added" on each other at the way back. If this is indeed what you want, you may need to change your code to something like this:

private function myRecursiveFunction()
{
  $results = [];
  //stuff related to $results
  ...
  if(!$done){
     .....
     // Add the computed results of the recursive call to our data stack
     $results[] = $this->myRecursiveFunction();
    }
  // Return the entire result array
  return $results;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.