skip to Main Content

main folder is home – with subfolders and txt files – on various levels
I need the list of entire folders tree – and count txt files inside each of them
This code gives the folders but count is always – 0
I suppose paths to folders and not only folder names – are required, but can’t see – how to get them.

   function rscan ($dir) {
      $all = array_diff(scandir($dir), [".", ".."]);
      foreach ($all as $ff) {
        if(is_dir($dir . $ff)){
          echo $ff . "n";  // it works
          $arr = glob($ff . "/*.txt");
          echo count($arr) . "n";  // always 0
          rscan("$dir$ff/");
        }
      }
    }
     
    rscan("home/");

2

Answers


  1. Line 6

    $arr = glob($ff . "/*.txt");
    

    Change to the code below:

    $arr = glob($dir.$ff . "/*.txt");
    
    Login or Signup to reply.
  2. An alternate implementation:

    <?php
    function glob_recursive($pattern, $flags = 0): Int {
        $files = glob($pattern, $flags);
        $count = count($files);
            
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
            $count += glob_recursive($dir.'/'.basename($pattern), $flags);
        }
            
        return $count;
    }
    var_dump(glob_recursive('home/*.txt'));
    

    The output is something like:

    int(10)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search