On Stack Overflow there are several answers to the question of how to check if the directory is empty, but which is the fastest, which way is the most effective?
Answer 1: https://stackoverflow.com/a/7497848/4437206
function dir_is_empty($dir) {
$handle = opendir($handle);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
closedir($handle); // <= I added this
return FALSE;
}
}
closedir($handle); // <= I added this
return TRUE;
}
Answer 2: https://stackoverflow.com/a/18856880/4437206
$isDirEmpty = !(new \FilesystemIterator($dir))->valid();
Answer 3: https://stackoverflow.com/a/19243116/4437206
$dir = 'directory'; // dir path assign here
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
Or, there is a completely different way which is faster and more effective than these three above?
As for the Answer 1, please note that I added closedir($handle);
, but I'm not sure if that's necessary (?).
EDIT: Initially I added closedir($dir);
instead of closedir($handle);
, but I corrected that as @duskwuff stated in his answer.