Well, still nobody came up with the clearest and quite short solution:
function isEmptyFolder($dir): bool
{
return scandir($dir) === ['.', '..'];
}
For older PHP versions:
function isEmptyFolder($dir)
{
return scandir($dir) === array('.', '..');
}
But normally we want to check before if the folder exists, because scandir will throw an exception if the folder doesn't exist. So if you want to ensure the folder exists but is empty (especially before the use of rmdir), use this:
function isEmptyFolder($dir): bool
{
return is_dir($dir) && is_readable($dir) && scandir($dir) === ['.', '..'];
}
If you consider a non-existing folder technically as empty (well, somehow it is) then use this:
function isEmptyFolder($dir): bool
{
return !is_dir($dir) || is_readable($dir) && scandir($dir) === ['.', '..'];
}
It's hard to consider all eventualities and how to react. What circumstances can you assume and which do you have to check? What if the name exists, but is a file, not a folder? What if the folder exists, but you don't have access to it? Do you want to create new files in it or delete it? Do you want to ignore the notorious Thumbs.db on Windows? It depends on your aim on that folder.
Regarding the performance issue the author of the accepted answer brings up: Well, I didn't do any performance checks, but I doubt that this is such a big issue. I bet scandir (now) uses the underlying OS function and this may have been optimized over various PHP versions to squeeze out more performance. So looping with PHP over files (now) is maybe slower even if you jump out very early. This might be only relevant with really big folders with many files. But then you might have a bigger problem than the performance thing to save some microseconds. Let's be honest: How often do you check for a folder being empty in a script? More than once? Maybe in an overnight maintenance cronjob but hardly in a regular webpage a user is waiting for.