Are there any specific PHP functions or features that can help manage variable depth in recursive functions?

When dealing with recursive functions that operate on data structures of variable depth, it can be challenging to keep track of the current depth level. One approach to manage variable depth in recursive functions is to pass an additional parameter to the function to keep track of the current depth level. This parameter can be incremented or decremented as the function recurses deeper or returns back up the call stack.

function process_data($data, $depth = 0) {
    // Base case: if data is not an array, process it at the current depth
    if (!is_array($data)) {
        echo "Processing data at depth $depth: $data\n";
        return;
    }

    // Recursive case: if data is an array, process each element recursively
    foreach ($data as $element) {
        process_data($element, $depth + 1);
    }
}

// Example usage
$data = [1, [2, [3, 4], 5], 6];
process_data($data);