© 2024 fjorge. All rights reserved.
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.
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:
And that is how you write a recursive function.