How can I ensure that each file extension in a directory is displayed only once, with a count of occurrences?

To ensure that each file extension in a directory is displayed only once with a count of occurrences, you can iterate through the files in the directory, extract the file extension for each file, and store it in an array. Then, use the array_count_values function to get the count of each unique file extension. Finally, loop through the array to display each file extension along with its count.

$directory = '/path/to/directory/';
$files = scandir($directory);
$extensions = [];

foreach ($files as $file) {
    if (is_file($directory . $file)) {
        $extension = pathinfo($file, PATHINFO_EXTENSION);
        $extensions[] = $extension;
    }
}

$extensionCounts = array_count_values($extensions);

foreach ($extensionCounts as $extension => $count) {
    echo $extension . ': ' . $count . PHP_EOL;
}