How can the use of associative arrays in PHP help in creating a hierarchical representation of folder contents?

When representing folder contents hierarchically, associative arrays in PHP can be used to store the folder structure. Each folder can be represented as a key in the array, with its contents (files or subfolders) stored as values. This allows for easy traversal and manipulation of the folder structure.

<?php

function buildFolderStructure($path) {
    $folderStructure = [];

    $files = scandir($path);

    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            if (is_dir($path . '/' . $file)) {
                $folderStructure[$file] = buildFolderStructure($path . '/' . $file);
            } else {
                $folderStructure[] = $file;
            }
        }
    }

    return $folderStructure;
}

// Example usage
$folderPath = '/path/to/folder';
$folderStructure = buildFolderStructure($folderPath);

print_r($folderStructure);

?>