What are the advantages of representing a file structure as a tree in PHP arrays?

Representing a file structure as a tree in PHP arrays allows for easy navigation and manipulation of the files and directories. It provides a hierarchical structure that mimics the actual file system, making it easier to organize and access files. Additionally, using a tree structure can simplify tasks such as searching for specific files, creating new directories, or moving files around.

function buildFileTree($path) {
    $tree = [];
    
    $files = scandir($path);
    
    foreach($files as $file) {
        if($file != '.' && $file != '..') {
            if(is_dir($path . '/' . $file)) {
                $tree[$file] = buildFileTree($path . '/' . $file);
            } else {
                $tree[] = $file;
            }
        }
    }
    
    return $tree;
}

$path = '/path/to/your/directory';
$fileTree = buildFileTree($path);

print_r($fileTree);