Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci totally lost me!
Thank you in advance ;-) Also how often do you use them in web development?
Best explanation I have found when I was learning that myself is here:http://www.elated.com/articles/php-recursive-functions/
Its because one thing:
The function when its called is created in memory (new instance is created)
So the recursive function IS NOT CALLLING ITSELF, but its calling other instance - so its not one function in memory doing some magic. Its couple of instances in memory which are returning themselves some values - and this behavior is the same when for example function a is calling function b. You have two instances as well as if recursive function called new instance of itself.
Try draw memory with instances on paper - it will make sense.
Recursion is a fancy way of saying "Do this thing again until its done".
Two important things to have:
Imagine a simple task: Sort a stack of books alphabetically. A simple process would be take the first two books, sort them. Now, here comes the recursive part: Are there more books? If so, do it again. The "do it again" is the recursion. The "are there any more books" is the test. And "no, no more books" is the base case.
Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)
The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.
This is a very simple example of factorial with Recursion:
Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.
hope this is usefull for you. :)
Recursion used for Kaprekar's constant
}
The function keeps calling itself with the result of the calculation until it reaches Kaprekars constant, at which it will return the amount of times the calculations was made.
/edit For anyone that doesn't know Kaprekars Constant, it needs an input of 4 digits with at least two distinct digits.
Simply put: A recursive function is a function that calls itself.