How to Write a Recursive Function with PHP
For the uninitiated, the recursive function can be a mind-bender. The concept, however, is not as difficult as it may seem at first glance. The difficulty of a recursive function is that it must have a definite way to exit the loop. Otherwise, you will have an eternal loop.
function loop_infinitely() {
loop_infinitely();
}
loop_infinitely();
This function will never exit, because the function is called within itself. Common means of exiting a recursive function include a counter, looping over an object or array of items, or a timer.
Hierarchy is a good example of a more complex form of recursion. If you are building a hierarchy tree and need it to be dynamic to account for different numbers and levels of users, you will need to either write nested loops to an insane depth, or write a recursive function. The latter is preferable.
To start, write the function that encapsulates the actions needing to be done on each level. For example
<?
function write_a_list() {
// Any output will very probably go outside the conditional, since it is being executed
// after having called the function from within the function. If necessary, you can pass
// a variable from within the function back to the function to check for grandchildren of
// the parent elements.
echo "
- ";
write_a_list();
on_this_level();
}
else {
// end the list when there are no more levels below to traverse.
echo "
And that is how you write a recursive function.