We will create a function 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.
while (list ($key, $val) = each ($result)) {
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);
while (list ($key, $val) = each ($result)) {
echo "$key ( $val ) <br>";
}
?>