note 42398 deleted from ref.dir by sniper

From: Date: Fri, 16 Dec 2005 00:00:54 +0000
Subject: note 42398 deleted from ref.dir by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-100263@lists.php.net to get a copy of this message
Note Submitter: joey at alegria dot co dot jp ---- 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; }

« previous php.notes (#100263) next »