Recursion vs. iteration in PHP
loops, php
Solution
Php is a special case. You will use less memory using the iterative solution. Moreover, function calls in PHP are costly, so it's better to avoid function calls when you can.
PHP will seg fault (on my system) trying to find the factorial of 100,000, but the iterative solution has no problems. Both of them execute practically instantaneously, though.
Of course, factorial of a much smaller number is `INF`, but this could also be applied to a much slower growing function.
If we're not talking about PHP or another scripting langauge, then there is no standard. It's good to know how to do it both ways. I would go with whichever leads to the cleanest code.
Problem
Iterative factorial function: ``` function factorial($number) { $result = 1; while ($number > 0) { $result *= $number; $number--; } return $result; } ``` Recursive factorial function: ``` function factorial($number) { if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } ``` I have to develop a function to calculate factorial in my PHP program. I figured it out that I could do it in above both ways. - What I don't know is which method is better to used and why? - What's the industry standard? - How can I select one of the methods between above two? - What's the condition to determine which one is better? I know It's a lot of questions but since I'm new to PHP and hope someone will help me out. Given that, actually the function I'm using is not just factorial. It has got some other lines too which do some other tasks. For the sake of simplification let's assume that these are the two functions. So anyone can understand my question rather complexing it for no reason. What I'm basically referring to is the recursion vs. iteration in PHP.