I came across this snippet today on the PHP manual page.. The page was actually about a function called scandir() which lists all files in a directory. This is of interest as I have always used the old school opendir() system to achieve this. The point however was that browsing the comments, I noticed this.
<?php // This is a function to count the number of files of a directory function countFiles($dir){ $files = array(); $directory = opendir($dir); while($item = readdir($directory)){ // We filter the elements that we don't want to appear ".", ".." and ".svn" if(($item != ".") && ($item != "..") && ($item != ".svn") ){ $files[] = $item; } } $numFiles = count($files); return $numFiles; } ?>
It made me chuckle. I remember writing massive amounts of code like this. I’m not laughing at the coder, but more at the huge amount of code to produce not a lot. Also the complete neglect for memory consumption by populating an array with every item in a directory. Doesn’t seem bad until you have 30,000 files in a dir and it starts to get noticed.
Anyway, putting my money where my mouth is, I wrote this in a few minutes (Yep, it leverages the axact function this all started with).
<?php function countFiles($dir = string) { $count = 0; foreach(scandir($dir) as $file) if(!in_array($file, array('.','..','.svn'))) $count++; return $count; }
My code;
- Doesn’t fill an array for no reason
- Doesn’t check for each $item, one after another
- Doesn’t count the array.
- Doesn’t pass the counted value to an obsolete variable.
Love to hear your thoughts.