PHP – Count the number of files in a Directory / folder

I was working on a PHP project and needed to display an error message when a given folder / directory is empty.

Below is a function that count the number of files (and/or folder) in a folder or directory.


< ?php
function countFolder($dir) {
	return (count(scandir($dir)) - 2);
}

To use the function, pass the directory to be counted as the function’s argument.

Note: i subtracted “2” from the gross-count to get the final net-count because PHP include (.) and (..) among the file and directory returned by scandir()

Say we want to count the number of files in folder “/home/tech4sky”.


<?php
echo countFolder('/home/tech4sky');

Alternatively, you can use a line of code to get the count number like so;


echo (count(scandir('/home/tech4sky')) - 2);
Don’t miss out!
Subscribe to My Newsletter
Invalid email address