What is the best way to count all *.jpg files in a folder with subfolders using PHP?

To count all *.jpg files in a folder with subfolders using PHP, we can use the RecursiveDirectoryIterator and RecursiveIteratorIterator classes to iterate through all directories and files recursively. We can then use a regular expression to filter out only the *.jpg files and count them.

$directory = new RecursiveDirectoryIterator('path/to/folder');
$iterator = new RecursiveIteratorIterator($directory);
$count = 0;

foreach($iterator as $file) {
    if(preg_match('/\.jpg$/', $file)) {
        $count++;
    }
}

echo "Total number of *.jpg files: " . $count;