Skip to content
Advertisement

Count files and subfolders in directory

I am writing a script which counts all files and folders recursively. I tried two approaches but each of these returns a different value: Script 1: 2376 Script 2: 2178

Here are the two scripts:

$source = 'folder';
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $file) {
    $result[] = $file.'<br />';
}
echo count($result).'<br />';
    function listFolders($dir) {
    if($dh = opendir($dir)) {
        $files = Array();
        $inner_files = Array();
        while($file = readdir($dh)) {
            if($file != "." && $file != "..") {
                if(is_dir($dir . "/" . $file)) {
                    $inner_files = listFolders($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
                } else {
                    array_push($files, $dir . "/" . $file);
                }
            }
        }
        closedir($dh);
        return $files;
    }
}
foreach (listFolders($source) as $key=>$file){
    $result2[] = $file ."<br />";
}
echo count($result2);

Is one of the scripts correct? What am I missing?

Advertisement

Answer

If your first example with RecursiveIterator, you are also counting the dot directories. In your second example, you cut them out.

Use this:

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {

    $result[] = $file.'<br />';
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement