How can recursive functions be utilized to create and manipulate hierarchical structures in PHP?

Recursive functions can be utilized to create and manipulate hierarchical structures in PHP by allowing a function to call itself within its definition. This is particularly useful when dealing with nested data structures like trees or directories. By recursively traversing through the structure, you can perform operations at each level and easily manipulate the hierarchy.

// Example of a recursive function to print a nested array
function printNestedArray($array, $indent = 0) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            echo str_repeat(' ', $indent) . $key . ":\n";
            printNestedArray($value, $indent + 4);
        } else {
            echo str_repeat(' ', $indent) . $key . ": " . $value . "\n";
        }
    }
}

// Example usage
$data = [
    'name' => 'John',
    'age' => 30,
    'children' => [
        'name' => 'Alice',
        'age' => 5
    ]
];

printNestedArray($data);