How can a recursive function in PHP be used to read all sub-folders of a directory and store them in an array?

To read all sub-folders of a directory and store them in an array using a recursive function in PHP, we can create a function that iterates through all the files and folders in a directory. When a sub-folder is encountered, the function can call itself recursively to read its contents as well. This way, we can build an array containing all the sub-folders within a directory.

function readSubFolders($dir) {
    $subFolders = [];
    
    $files = scandir($dir);
    
    foreach($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        
        $fullPath = $dir . '/' . $file;
        
        if (is_dir($fullPath)) {
            $subFolders[] = $fullPath;
            $subFolders = array_merge($subFolders, readSubFolders($fullPath));
        }
    }
    
    return $subFolders;
}

$directory = 'path/to/directory';
$subFoldersArray = readSubFolders($directory);

print_r($subFoldersArray);