Recursion in PHP
(Page 1 of 4 )
Learn how recursion works and how to implement it in PHP.
By : David Stockton
The first thing you need to do in order to create a recursive function is to create a recursive function unless you already have a recursive function, in which case, just use your recursive function.
Ok, more seriously, a recursive function is just a function that calls itself. In order to make a recursive function not explode all over itself, though, it is important to keep some ideas in mind.
The first idea is that some part of the recursive function must have a value that is obtainable without another call to the function. If you don't have this, you run the danger of making an infinite loop, which is a function that continually calls itself forever. Realistically, the computer will run out of memory before forever occurs, or your computer will lose power, or you'll reboot the computer or kill the process, but it can still be a pain.
So there are several things to keep in mind when you're creating a recursive function:1) You must have an exit condition (the part of the function that can be calculated without further calls to that function)2) Each recursive call must be different than the one before it.3) You must believe it works.
So, let's try a simple one. The factorial function and the Fibonacci sequences lend themselves easily to recursion, so let's start with the factorial function.
Next: Factorials >>
More Miscellaneous Articles
More By Codewalkers