I am working on a PHP function that will recursively remove all sub-folders that contain no files starting from a given absolute path.
Here is the code developed so far:
function RemoveEmptySubFolders($starting_from_path) {
// Returns true if the folder contains no files
function IsEmptyFolder($folder) {
return (count(array_diff(glob($folder.DIRECTORY_SEPARATOR."*"), Array(".", ".."))) == 0);
}
// Cycles thorugh the subfolders of $from_path and
// returns true if at least one empty folder has been removed
function DoRemoveEmptyFolders($from_path) {
if(IsEmptyFolder($from_path)) {
rmdir($from_path);
return true;
}
else {
$Dirs = glob($from_path.DIRECTORY_SEPARATOR."*", GLOB_ONLYDIR);
$ret = false;
foreach($Dirs as $path) {
$res = DoRemoveEmptyFolders($path);
$ret = $ret ? $ret : $res;
}
return $ret;
}
}
while (DoRemoveEmptyFolders($starting_from_path)) {}
}
As per my tests this function works, though I would be very delighted to see any ideas for better performing code.