Search code examples
phpchildrendir

PHP - fastest way to find if directory has children?


I'm building a file browser, and I need to know if a directory has children (but not how many or what type).

What's the most efficient way to find if a directory has children? glob()? scandir() it? Check its tax records?

Edit

It seems I was misunderstood, although I thought I was pretty clear. I'll try to restate my question.

What is the most efficient way to know if a directory is not empty? I'm basically looking for a boolean answer - NOT EMPTY or EMPTY.

I don't need to know:

  • how many files are in the directory
  • what the files are
  • when they were modified
  • etc.

I do need to know:

  • does the directory have any files in it at all

efficiently.


Solution

  • I think this is very efficient:

    function dir_contains_children($dir) {
        $result = false;
        if($dh = opendir($dir)) {
            while(!$result && ($file = readdir($dh)) !== false) {
                $result = $file !== "." && $file !== "..";
            }
    
            closedir($dh);
        }
    
        return $result;
    }
    

    It stops the listing of the directories contents as soon as there is a file or directory found (not including the . and ..).