What are some alternative approaches to using glob() and count() for file checks in PHP, especially when dealing with empty directories or directories with non-matching file types?

When using glob() and count() for file checks in PHP, one issue that arises is when dealing with empty directories or directories with non-matching file types. One alternative approach is to use the scandir() function to get the list of files in a directory, filter out any unwanted files, and then count the remaining files. This approach allows for more flexibility in handling different scenarios when checking files in a directory.

// Get list of files in directory
$files = array_diff(scandir($directory), array('..', '.'));

// Filter out unwanted files (e.g., non-matching file types)
$filteredFiles = array_filter($files, function($file) {
    return pathinfo($file, PATHINFO_EXTENSION) == 'txt'; // Change 'txt' to desired file type
});

// Count the remaining files
$numFiles = count($filteredFiles);

echo "Number of txt files in directory: " . $numFiles;