How can PHP's scandir function be used to determine the number of files in a directory, and what are its limitations in this context?

To determine the number of files in a directory using PHP's scandir function, you can use the count function on the array returned by scandir after filtering out the "." and ".." entries. However, the scandir function will also include directories in the count, so you may need to check if each entry is a file before counting it.

$directory = "/path/to/directory";
$files = array_diff(scandir($directory), array('..', '.'));
$numFiles = 0;

foreach ($files as $file) {
    if (is_file($directory . '/' . $file)) {
        $numFiles++;
    }
}

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