How to use ‘depth’?

On recursive methods, I usually add a $depth parameter:

function my_function($depth = -1)
{
    if ($depth === 0) {
        return array(); // or any other value insisting an empty or false result
    }
    // do something
    $result = array();
    while ($some_condition) {
        $result = array_merge($result, my_function($depth - 1)); // decrease $depth value
    }
    // maybe do something more
    return $result;
}

When calling my_function() without a $depth parameter, there won’t be any restriction in the depth. But if you provide a $depth value, it’ll stop recursion when the $depth value is zero.

Don’t use $depth-- in a loop. $depth - 1 is the correct way.