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;
}
Related Questions
- What are the potential pitfalls when using preg_replace to remove line breaks and spaces in PHP?
- What are the potential pitfalls of manually sending data via a GET request in PHP?
- In PHP, what considerations should be taken into account when displaying user-generated content with HTML markup in previews or views?