Checking if a folder is empty or not using PHP

At times we need to check if a folder is empty or not before performing an operation on it. For this, I have written a function which returns TRUE if any file or folder is found inside the folder and FALSE if the folder is empty.

function checkFolderIsEmptyOrNot ( $folderName ){
$files = array ();
if ( $handle = opendir ( $folderName ) ) {
while ( false !== ( $file = readdir ( $handle ) ) ) {
if ( $file != “.” && $file != “…” ) {
$files = $file;
}
}
closedir ( $handle );
}
return ( count ( $files ) > 0 ) ? TRUE: FALSE;
}
Eliza

How about this? From the is_dir manual page.


public static function isEmptyDir($dir){ 
     return (($files = @scandir($dir)) && count($files) <= 2); 
}

Your function is not bad either but why you continue reading all the files and folder if you found a file or folder in it. Just check as if a file found and terminate the loop with break.


function checkFolderIsEmptyOrNot ( $folderName ){
    $files = array ();
    if ( $handle = opendir ( $folderName ) ) {
        while ( false !== ( $file = readdir ( $handle ) ) ) {
            if ( $file != "." && $file != ".." )
                $files[] = $file;
            if(count($files) >= 1)
                break;
        }
        closedir ( $handle );
    }
    return ( count ( $files ) > 0 ) ? TRUE: FALSE;
}

return (count(dir('here') === 2);