$dir is empty or not

if(is_dir($dir)){

if(file_exists($dir.'/myFile.php')){

echo "Yes, there is a file named [COLOR="#0000CD"]myFile.php[/COLOR]";
}else{
echo "No, [COLOR="#0000CD"]myFile.php[/COLOR] is not there.";
}

}

The code above works file.

The would-be code below doesn’t work correctly, but I hope it shows what I want.

if(is_dir($dir)){

if(file_exists($dir.'/'.[COLOR="#FF0000"]*.*[/COLOR]')){

echo "Yes, there is a file or subDirectory at least one or more than one."
}else{
echo "No, its empty.";
}

}

I like to get the directory is empty or NOT.

Here are 2 simple functions to check if a directory is empty or not.


function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL;
  return (count(scandir($dir)) == 2);
}

A better version


function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL;
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      return FALSE;
    }
  }
  return TRUE;
}

You should find plenty of answers searching on google right away

The both code work fine each.
Thank you very much, silv3r.m00n.

By the way,
Why does the 2nd function is the better version?
(The 1st function is shorter and seems more understandable.)

the first version uses scandir and hence checks all files in the directory. this will be slow if the directory has lots of file.

since we just need to know if the directory is empty or not, its faster to check if the first file is other than “.” and “…” (these are the directory paths actually to current directory and parent directory)
that way if a file name is found other than “.” and “…” using readdir, the entire list of files might not be read and the function would be faster.