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?
Laymens terms:
A recursive function is a function that calls itself
A bit more in depth:
If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.
What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.
In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.
Although I cannot compete with the directory example, I hope this helps somewhat.
(4/20/10) Update:
It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,
Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.
An example of a tree structure in javascript and a recursive function to 'walk' the tree.
--
To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.
In this example, we'll get the maximum depth of the tree
Finally we call the function
A great way of understanding recursion is to step through the code at runtime.
It is very simple, when a function calls itself for accomplishing a task for undefined and finite number of time. An example from my own code, function for populating a with multilevel category tree
An example would be to print every file in any subdirectories of a given directory (if you have no symlinks inside these directories which may break the function somehow). A pseudo-code of printing all files looks like this:
The idea is to print all sub directories first and then the files of the current directory. This idea get applied to all sub directories, and thats the reason for calling this function recursively for all sub directories.
If you want to try this example you have to check for the special directories
.
and..
, otherwise you get stuck in callingprintAllFiles(".")
all the time. Additionally you must check what to print and what your current working directory is (seeopendir()
,getcwd()
, ...).