Remove empty subfolders with PHP
Posted
by Dmitry Letano
on Stack Overflow
See other posts from Stack Overflow
or by Dmitry Letano
Published on 2009-12-02T15:12:05Z
Indexed on
2010/04/08
14:23 UTC
Read the original article
Hit count: 263
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.
© Stack Overflow or respective owner