W3docs

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.

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:

Example of using the scandir() function to get an array of files in a directory in PHP

<?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";
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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.

Example of using glob() function to check if directory is empty in PHP

<?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.