The old each() function was removed from PHP 8. Use foreach for the result array, and count only regular files when you want extension statistics.
<?php
$directory = __DIR__;
$counts = [];
foreach (scandir($directory) ?: [] as $entry) {
$path = $directory . DIRECTORY_SEPARATOR . $entry;
if (!is_file($path)) {
continue;
}
$extension = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
$extension = $extension !== '' ? $extension : '[no extension]';
$counts[$extension] = ($counts[$extension] ?? 0) + 1;
}
ksort($counts);
foreach ($counts as $extension => $total) {
echo htmlspecialchars($extension, ENT_QUOTES, 'UTF-8') . ' (' . $total . ')
';
}
?>
$path = '../../php_tutorial/'; // change the path
$ar=scandir($path); // Array with all file and directory names
From this we will remove the current directory and parent directory dots ( single and double dots ) by using array_diff()
$ar=array_diff($ar,array('.','..'));// remove dots

my_pathinfo() to get the name of file extensions of the elements of the array. We will use array_map() function to apply our function my_pathinfo() on all the elements ( output of scandir() ) of the array.
$extensions=array_map('my_pathinfo',$ar); // Array with all file extensions
// function to get file extensions //
function my_pathinfo($str){
return (pathinfo($str, PATHINFO_EXTENSION)); // return the file extension
}
We will use array_count_values() to create an array with extensions used and frequency of their occurrence.
$result=array_count_values($extensions);
We will display all the elements of the array
foreach ($result as $key => $val) {
echo "$key ( $val ) <br>";
}
The full code is here. Change the $path to match your directory path.
<?Php
$path = '../../php_tutorial/'; // change the path
$ar=scandir($path); // Array with all file and directory names
$ar=array_diff($ar,array('.','..'));// remove dots
// Each element is executed through callback function //
$extensions=array_map('my_pathinfo',$ar); // Array with all file extensions
// function to get file extensions //
function my_pathinfo($str){
return (pathinfo($str, PATHINFO_EXTENSION)); // return the file extension
}
//Count the frequency of occurrence of elements //
$result=array_count_values($extensions);
foreach ($result as $key => $val) {
echo "$key ( $val ) <br>";
}
?>
Here is the output
zip ( 5 )
php ( 61 )
txt ( 6 )
htm ( 3 )
js ( 3 )
css ( 3 )
xml ( 3 )
( 7 )
csv ( 2 )
jpg ( 2 )
There are 7 directories present so there is a listing of number 7 without any file extension
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.