counting files in directories

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

counting files in directories

Post by Luke »

I know I can just read all the files in the directory with readdir() but is there a more effective way to do this if i just wish to know how many files are inside of a directory?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

my favorite, but slightly complicated for some

Code: Select all

$num = count(array_filter(glob('/some/path/*'),'is_file')));
defect
Forum Newbie
Posts: 8
Joined: Wed Jun 14, 2006 2:59 pm
Location: Stockholm, Sweden

Post by defect »

not sure about effectiveness but i like this way:

Code: Select all

$num = shell_exec("ls /path/to/dir|wc -l");
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Using shell commands is highly unrecommended. Feyd's method is quite quick. If you really wanted things to work out nice, you'd define global_countFilesInDir($directory) function and implement it there, so that you could change it if something better came along.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

I've never even used the shell_exec function. That is very interesting... I will look into that (not for this, but just because it's interesting).

Thanks feyd... that worked very nicely.
Post Reply