Since I needed this too, I was curious about which alternative was the fastest.
I found that if all you need is the number of files - Baba's solution is much faster than others. I was very surprised.
Try it yourself:
<?php define('MYDIR', '...'); foreach (array(1, 2, 3) as $i) { $t = microtime(true); $count = run($i); echo "$i: $count (".(microtime(true) - $t)." s)\n"; } function run ($n) { $func = "countFiles$n"; $x = 0; for ($f = 0; $f < 5000; $f++) $x = $func(); return $x; } function countFiles1 () { $dir = opendir(MYDIR); $c = 0; while (($file = readdir($dir)) !== false) if (!in_array($file, array('.', '..'))) $c++; closedir($dir); return $c; } function countFiles2 () { chdir(MYDIR); return count(glob("*")); } function countFiles3 () // Fastest method { $f = new FilesystemIterator(MYDIR, FilesystemIterator::SKIP_DOTS); return iterator_count($f); } ?>
Testing: (obviously, glob() does not take dot files into account)
1: 99 (0.4815571308136 s) 2: 98 (0.96104407310486 s) 3: 99 (0.26513481140137 s)
vbwx Oct 22 '13 at 9:29 2013-10-22 09:29
source share