How can recursion be utilized in PHP to create a directory tree structure from file paths?

To create a directory tree structure from file paths in PHP using recursion, we can split each file path into its individual directories and create nested arrays representing the directory structure. Recursion can be used to iterate through each directory level and build the nested arrays accordingly.

function buildDirectoryTree($paths) {
    $tree = [];
    
    foreach ($paths as $path) {
        $parts = explode('/', $path);
        $node = &$tree;
        
        foreach ($parts as $part) {
            $node = &$node[$part];
        }
    }
    
    return $tree;
}

// Example usage
$paths = [
    'dir1/dir2/file1.txt',
    'dir1/dir3/file2.txt',
    'dir1/file3.txt'
];

$directoryTree = buildDirectoryTree($paths);
print_r($directoryTree);