How can I use PHP to check if a directory is empty?
You can use the scandir()
function to get an array of files in a directory, and then check the length of the array. If the length is 0 or 2 (assuming the directory contains only "." and ".."), then the directory is empty. Here's an example:
<?php
$dir = '/path/to/directory';
$files = scandir($dir);
if(count($files) == 0 || count($files) == 2) {
echo "Directory is empty";
} else {
echo "Directory is not empty";
}
Watch a video course
Learn object oriented PHP
You can also use glob()
function to check if directory is empty or not by passing the path of the directory and file pattern to it.
<?php
$dir = '/path/to/directory';
if (count(glob($dir . '/*')) === 0) {
echo "Directory is empty";
} else {
echo "Directory is not empty";
}
Please note that this only returns the files in the top level of the directory, if you want to check for files in subdirectories also, you'll need to use recursion.