note 42398 added to ref.dir

From: Date: Fri, 14 May 2004 16:41:05 +0000
Subject: note 42398 added to ref.dir
Groups: php.notes 
Request: Send a blank email to php-notes+get-69618@lists.php.net to get a copy of this message
After some consideration, this seems to be the most concise and elegent method I can devise for recursively traversing a directory (i.e. all subdirectories as well). It returns an Array containing all entries. It DOES NOT require global variables either. To make it return only other directories or only files, insert one of the following where indicated: DIR ONLY OPTION 1: if(is_dir($full_path)){ $list[]=$full_path; } FILE ONLY OPTION 2: if(is_file($full_path)){ $list[}=$full_path; } function make_tree($path){ //where $path is your source dir. $handle=opendir($path); while($a=readdir($handle)){ if(!preg_match('/^\./',$a)){ $full_path="$path/$a"; $list[]=$full_path; // REPLACE WITH OPTION IF NEEDED. if(is_dir($full_path)){ $recursive=make_tree($full_path); for($n=0; $n<count($recursive); $n++){ $list[]=$recursive[$n]; } } } } closedir($handle); return $list; } If conciseness is what you are after, the above is rock solid. However, beware of passing huge or unknown filesystem's paths as it can eat memory unless you impose a recursive level limit. The above can be very easily modified to limit recursive levels. See the below, limit-safe example. function make_tree($path){ //where $path is your source dir. $handle=opendir($path); while($a=readdir($handle)){ if(!preg_match('/^\./',$a)){ $full_path="$path/$a"; $list[]=$full_path; if((is_dir($full_path))&&(!preg_match('/(\/.+){6,}/',$full_path))){ //where {6,} is the maximum recursives $recursive=make_tree($full_path); for($n=0; $n<count($recursive); $n++){ $list[]=$recursive[$n]; } } } } closedir($handle); return $list; } ---- Manual Page -- http://www.php.net/manual/en/ref.dir.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42398 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42398&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42398&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#69618) next »