How to Write a Recursive Function with PHP

January 3, 2013

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 "
  • This is the list for the current row.
  • "; } function on_this_level() { // This is where the action happens. if(levels_below()) { // Call this function as long as there are still levels to go. The function is not // written here, but it would check whatever conditions would be true of your result // which would specify a child element. In this case, the levels_below() would need to // contain the conditions which would prevent an infinite loop. // Start a list, because the elements below must go inside of it. echo "
      "; write_a_list(); on_this_level(); } else { // end the list when there are no more levels below to traverse. echo "
    "; } } // The function just needs to be called once outside the function so that it triggers. // I have chosen to loop over a list to show a little bit of added complexity. foreach ($items as $item) { on_this_level(); } ?>

    And that is how you write a recursive function.

    Stay in Touch!

    Subscribe to our newsletter.

    Solutions Architecture

    browse through our blog articles

    Blog Archive