How to check if directory is empty or not in PHP


sometimes we need to check if a directory is empty or not before performing an operation on this directory.For this, I have written a function which returns “directory is not empty” if any file or folder is found inside the folder and returns “directory is empty” if the folder is empty.


PHP Program to check if directory is empty or not in PHP 


<?php
function dir_is_empty($dir) 
{
  // check whether a file exists in a directory and is readable
  if (!is_readable($dir)) return NULL; 
   
  return (count(scandir($dir)) == 2); 
}
  
   
if (dir_is_empty("d:/xampp")) 
    echo "directory is empty !!!";
else
    echo "directory is not empty !!!";

 


Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *