Recursive function: Call php function itself

Andrew Surdu picture Andrew Surdu · Sep 5, 2013 · Viewed 22.6k times · Source

I just want to make sure I do it right and this will not create any conficts.

I have a function which calls itself and need your approval if it's OK or not to do so?

<?php

function determine($the_array){
    foreach ($the_array as $key => $value) {
        switch ($key) {
            case 'in':
                    echo $value;
                break;

            case 'out':
                    echo $value;
                break;

            case 'level':
                    echo '<ul>';
                    determine($value);
                    echo '</ul>';
                break;

        }
    }

}

This is the array:

$the_array = array(
    'in' => '<li>Simple IN</li>',
    'out' => '<li>Simple OUT</li>',
    'level' => array(
            'in' => '<li>Simple IN 2</li>',
            'out' => '<li>Simple OUT 2</li>',
            'level' => array(
                'in' => '<li>Simple IN 3</li>',
                'out' => '<li>Simple OUT 3</li>'
            ),
        ),
);

And here is the final init:

echo '<ul>';
determine($the_array);
echo '</ul>';

The result is just how I wanted to be, it works great, but I don't know if this is a good practice.

Answer

Fluffeh picture Fluffeh · Sep 5, 2013

Recursive functions are OK - but dangerous if you aren't sure you know what you are doing. If there is any chance that a function will end up in a recursive loop (where it keeps calling itself over and over) you will either time out, run out of memory or cause a zombie apocalypse.

Think of recursive calls as a really, really sharp knife - in the hands of an experienced chef, it's a match made in heaven, in the hands of the dishwasher, it is a lost finger waiting to happen.

PHP tries to play nice, and limits a recursive depth to 100 by default (though this can be changed) but for almost all cases, if your recursive depth gets to 100, the accident has already happened and PHP reacts by stopping any additional pedestrians from wandering into traffic. :)