Best way to check if php directory is empty

Is there a better way to check if a directory is empty than parsing it?

+5
source share
2 answers

Do not think so. The shortest / fastest way I can think of is the following, which should work as far as I can tell.

function dir_is_empty($path)
{
    $empty = true;
    $dir = opendir($path); 
    while($file = readdir($dir)) 
    {
        if($file != '.' && $file != '..')
        {
            $empty = false;
            break;
        }
    }
    closedir($dir);
    return $empty;
}

This should go through no more than three files. Two .and ..and maybe all that comes next. If something comes next, it is not empty, and if not, then it is empty.

+8
source

Not really, but you can try to remove it. If it fails, it is not empty (or you just cannot delete it;))

function dirIsEmpty ($dir) {
  return rmdir($dir) && mkdir($dir);
}

Update:

, , " ", ;)

function dirIsEmpty ($dir) {
  return count(glob("$dir/**/*")) === 0:
}

, , ( .).

-1

All Articles