Home  >  Article  >  Backend Development  >  Function to traverse all files and subfolders in a folder

Function to traverse all files and subfolders in a folder

WBOY
WBOYOriginal
2016-07-25 09:02:30955browse
The legend is a written test question for Sina PHP Engineer
  1. function my_dir($dir){
  2. $files=array();
  3. if(@$handle=opendir($dir)){//Note that you need to add an @ here, otherwise there will be warning error message:)
  4. while(($file=readdir($handle))!==false){
  5. if($file!=".." && $file!="."){//Exclude the root directory ;
  6. if(is_dir($dir."/".$file)){//If it is a subfolder, perform recursion
  7. $files[$file]=my_dir($dir."/".$file);
  8. }else{//Otherwise, store the file name in the array;
  9. $files[]=$file;
  10. }
  11. }
  12. }
  13. closedir($handle);
  14. return $files;
  15. }
  16. }
  17. / /The following is the test
  18. $q_array=my_dir('E:/115');
  19. print_r($q_array);
  20. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn