0

I have the following function:

function listFiles($dir, $results = array()){       
    $entities = is_dir($dir) ? array_values(array_diff(scandir($dir), array('..', '.'))) : false ;  
    if( $entities )
        foreach( $entities as $e ) {
            $path = $dir.'/'.$e;
            if( is_dir($path) ) {
                listFiles($path, $results);
            }   
            $results[] = $path;
        }
        return $results;
    }
print_r(listFiles('/home/apps/public_html/test_folder'));

Although this works somehow the array has only the first branch of the directory. But if I echo the path inside foreach I get the path of every file from all folders and subfolders and so on.

Probably this is something very small but I can't figure out what and I could use some help. Thank you.

alex
  • 5,467
  • 4
  • 33
  • 43
Petru Lebada
  • 2,167
  • 8
  • 38
  • 59
  • 1
    Possible duplicate of [PHP list all files in directory](http://stackoverflow.com/questions/3826963/php-list-all-files-in-directory) – u_mulder Aug 09 '16 at 10:02
  • It's the same title for a different problem,if you read the question closely – Petru Lebada Aug 09 '16 at 10:08
  • If you read the provided duplicate closely - you will find more similar questions there, but it's too hard, I understand. – u_mulder Aug 09 '16 at 11:20

1 Answers1

0

inside your recursive function if a subdir is found you call the function itself with the subdir but it's results are not handled, not assigned to any variable so they are lost, you should push it to your results like this:

if( is_dir($path) ){
    $results[] = listFiles($path, $results);
} 
Volkan Ulukut
  • 4,230
  • 1
  • 20
  • 38
  • how do you mean? it should return subdir's as arrays which create multidimensional arrays for subdir's for the end result. – Volkan Ulukut Aug 09 '16 at 10:25