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?
Asked
Active
Viewed 1.9k times
14
-
5[`rmdir`](http://php.net/manual/en/function.rmdir.php) will fail for non-empty directory, so just `$deleted = @rmdir('/path/to/folder');` – dev-null-dweller Sep 08 '13 at 15:56
-
Thanks... going the `glob` way as suggested by both @Matteo and *Jeffman* – ErickBest Sep 08 '13 at 16:14
2 Answers
31
Use glob
:
if (count(glob("path/*")) === 0 ) { // empty
A nice thing about glob
is that it doesn't return .
and ..
directories.
-
5
-
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;
}
-
Is this going to be quicker and most effective way than the `glob` suggested by @jeffman ? – ErickBest Sep 08 '13 at 16:01
-
2I benchmarked the two solutions and actually Jeffman one's is faster (on one folder). Jeffman: `5.388E-5 seconds` My solution: `2.909E-5 seconds` – mcont Sep 08 '13 at 16:08
-
1