Do not tell me why this code goes into endless recursion, because of what it eats all the RAM and stops working?

public function getFiles($dir, $array = []){ if(is_dir($dir)){ $directory = scandir($dir); foreach($directory as $file){ if($file != "." and $file != ".."){ if(is_dir($dir."/".$file)){ $directory_files = $this->getFiles($dir."/".$file, $array); $array = array_merge($array, $directory_files); } $array[] = $dir."/".$file; } } } $array[] = $dir; return $array; } 
  • Maybe a lot of nested folders, who knows - Alexey Shimansky
  • 96 files considered a lot? And array_merge is used to add paths from a subfolder (re-call this function). - Eddir
  • To begin with, it would be possible to declare an array in the function via an ampersand &$array - LamerXaKer

1 answer 1

Corrected your code, so it should work ( not tested ).

  function getFiles($dir) { $result = array(); $directory = scandir($dir); foreach ($directory as $key => $file) { if (!in_array($file,array(".",".."))) { if (is_dir($dir."/".$file)) $result[$file] = getFiles($dir."/".$value); else $result[] = $file; } } return $result; } var_dump(getFiles("some_dir")); 
  • one
    Please try to write more detailed answers. I am sure the author of the question will be grateful for a detailed expert commentary explaining the code. - Nicolas Chabanovsky
  • Thank you very much. In one place only error corrected. Now perfect!) - Eddir