May 2017
Intermediate to advanced
340 pages
8h 16m
English
If we analyze our factorial function, we can see that it could be written using a simple iterative approach with a for or while loop, as shown here:
function factorial(int $n): int { $result = 1; for ($i = $n; $i > 0; $i--) { $result *= $i; } return $result; }
If this can be written as a simple iterative one, then why should we use recursion? Recursion is used to solve more complex problems. Not all problems can be solved iteratively so easily. For example, we need to show all the files in a certain directory. We can simply do this by running a loop to list all the files. However, what if there is another directory inside it? Then, we have to run another loop to get all those files inside that directory. ...
Read now
Unlock full access