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
- How can one handle negative interactions or unhelpful responses in PHP forums effectively?
- What are potential reasons for a file downloaded via PHP to have a smaller size than expected?
- How can PHP developers optimize cookie handling across multiple pages in a web application to maintain user session information?