14

I got a root directory with 100s of dynamically generated folders. As time goes some of these folders will need to be extirpated from system on the condition that this(ese) directories(s) must be empty. What would be the best shortest, easiest and/or most effective way to achieve that?

ErickBest
  • 4,586
  • 5
  • 31
  • 43

2 Answers2

31

Use glob :

if (count(glob("path/*")) === 0 ) { // empty

A nice thing about glob is that it doesn't return . and .. directories.

  • 5
    use `GLOB_NOSORT` flag to increase performance – Preexo Apr 03 '14 at 17:02
  • but if ./.. are not reported, then such dir would not be deleted, as it is not empty ... so it seems to be not good for empty dir removal – Jeffz Oct 25 '15 at 22:24
  • This wrong way, glob() ignores hidden files by default, http://php.net/manual/ru/function.glob.php#68869 So, if you add the mask to get hidden files in glob() you've got the same solution, as @Matteo wrote below. – Vijit Jan 30 '17 at 07:35
  • Considering coding convenience this is efficient. Considering performance this may be bad if glob first need to deliver +1000 files for each dir to check after which count tells how many files there are. – Rbgo Web Oct 25 '17 at 09:01
8

You can count the items contained in the folder. The first two items are . and .., so just check the items count.

$files_in_directory = scandir('path/to');
$items_count = count($files_in_directory);
if ($items_count <= 2)
{
    $empty = true;
}
else {
    $empty = false;
}
Alexey
  • 5,898
  • 9
  • 44
  • 81
mcont
  • 1,749
  • 1
  • 22
  • 33