TheKeymaster
TheKeymaster

Reputation: 897

PHP - Directory browsing from recursive to iterative

Hello I am trying to make the following function iterative. It browses threw all directories and gives me all files in there.

function getFilesFromDirectory($directory, &$results = array()){
    $files = scandir($directory);

    foreach($files as $key => $value){
        $path = realpath($directory.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getFilesFromDirectory($path, $results);
            $results[] = $path;
        }
    }
    return $results;
}

I am sure that it is possible to make this function iterative but I really have no approach how I can do this.

Upvotes: 1

Views: 53

Answers (1)

JParkinson1991
JParkinson1991

Reputation: 1286

Your going to want to use a few PHP base classes to implement this.

Using a RecursiveDirectoryIterator inside of a RecursiveIteratorIterator will allow you to iterate over everything within a directory regardless of how nested.

Its worth noting when looping over the $iterator below each $item is an object of type SplFileinfo. Information on this class can be found here: http://php.net/manual/en/class.splfileinfo.php

<?php 

//Iterate over a directory and add the filenames of all found children
function getFilesFromDirectory($directory){
    //Return an empty array if the directory could not be found
    if(!is_dir($directory)){
        return array();
    }

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory)
    );

    $found = array();
    foreach($iterator as $item){
        if(method_exists($item, 'isFile') && $item->isFile()){
            //Uncomment the below to exclude dot files
            //if(method_exists($item, 'isDot') && $item->isDot()){
            //  continue;
            //}
            
            //Pathname == full file path
            $found[] = $item->getPathname();
        }
    }

    return $found;
}

An var_dump of some found files i did using this function as a test:

enter image description here

Hope this helps!

Upvotes: 3

Related Questions