I'm trying to list the folders on the directory which are not empty.

Dear Experts,

I use PHP.
I list all my folders with below code, however some of them are empty folders. But I want to list all my folders which are not empty.

how can I do that?
my code is like this

$dir    = 'myfoldername';
$files1 = scandir($dir);

foreach ($files1 as $bayikodu) {

 echo $bayikodu . "<br>";


Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
How many levels do you want to go down - a fixed number or to the end of the path?

You need (for each entry that is a dir) scandir that and see if the returned results > 2 (all folders will have . and .. entries)

$files = scandir($foldername);
if ($files > 2) {
   // not empty

Open in new window

However, this is a bit simplistic - what constitutes and empty folder? For instance if a folder has 2 other folders but neither of them has any files is the parent folder considered empty?

If you only want to go down one level you can do this
$dir    = 'myfoldername';
$result = getFolders($dir);
echo "<pre>" . print_r($result, true) . "</pre>";

function getFolders($root)
	$result = array();
	$files1 = scandir($root);
	foreach ($files1 as $bayikodu) {
		if (
			is_dir($root . "\\" . $bayikodu) && 
			$bayikodu != "." && 
			$bayikodu != ".." && 
			count(scandir($root . "\\" . $bayikodu)) > 2
		) {

			$result[] = $bayikodu;
	return $result;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BRMarketingAuthor Commented:
Thank you Julian Hansen.
Best regards.
Julian HansenCommented:
You are welcome
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.