What are the advantages of using a lookup array for counting file extensions in PHP scripts?
When counting file extensions in PHP scripts, using a lookup array can provide a more efficient and organized way to keep track of the count for each file extension. By using a lookup array, you can easily increment the count for a specific file extension without the need for multiple if statements or switch cases. This approach simplifies the code and improves readability.
// Initialize an empty lookup array to store the count for each file extension
$extensionCount = [];
// Get list of file extensions from a directory
$files = glob('path/to/directory/*.*');
// Loop through each file and count the occurrences of each file extension
foreach ($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (isset($extensionCount[$extension])) {
$extensionCount[$extension]++;
} else {
$extensionCount[$extension] = 1;
}
}
// Output the count for each file extension
foreach ($extensionCount as $extension => $count) {
echo "Extension: $extension, Count: $count\n";
}