December 2, 2011

codeigniter recursive function return problem

codeigniter recursive function return problem


If you are stuck too in recursive call of a function and not getting the value as return as expected so be sure about your instances. Because whenever a function being called either independently or recursively so it should be linked to the parent function to which it should report back instead of just performing some tasks like a subroutine. For example if you call a public function and then inside that function you call the same function again but you want to return some value conditionally not every time so it won’t work you are expecting because in true or false case it will return or not but in other case it will break that link which was a way back to parent function. Let me explain it with an example but before that i will tell you 2 rules for it as my experience:

  1. If you need to return a value conditionally then return values in both cases either you have to return something or not
  2. If you need to return a value conditionally but don’t want to return or not interested in this solution so return that recursive function call

Explanation – With Mistake

 

function recursive_func($param1,$param2,$iteration=0)

{

if($param1 exists in db where field2=$param2)

{

$iteration++;

recursive_func($param1,$param2,$iteration);

}

else

{

return “last->node”;
}

}

Explanation – Mistake Corrected

 

function recursive_func($param1,$param2,$iteration=0)

{

if($param1 exists in db where field2=$param2)

{

$iteration++;

return recursive_func($param1,$param2,$iteration);

}

else

{

return “last->node”;
}

}

In fact the essence i in returning the value for both true and false condition or remove the condition from recursion. Because when a nested function is called with “return” so that function gone as a separate thread which don’t know that if it has to report a parent function or not?

I hope this post will help those OOP geeks which seldom need to use recursion. Give your feedback and put your functions here if need any other solution regarding recursion. I will try my best to sort out the problem.

Last updated: March 19, 2014