If you have empty folder within empty folder within empty folder, you'll need to loop through ALL folders three times. All this, because you go breadth first - test folder BEFORE testing its children. Instead, you should go into child folders before testing if parent is empty, this way one pass will be sufficient.
function RemoveEmptySubFolders($path)
{
$empty=true;
foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
{
if (is_dir($file))
{
if (!RemoveEmptySubFolders($file)) $empty=false;
}
else
{
$empty=false;
}
}
if ($empty) rmdir($path);
return $empty;
}
By the way, glob does not return . and .. entries.
Shorter version:
function RemoveEmptySubFolders($path)
{
$empty=true;
foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
{
$empty &= is_dir($file) && RemoveEmptySubFolders($file);
}
return $empty && rmdir($path);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…