Current Location: Home> Latest Articles> How to Count Files in a PHP Directory: Complete Tutorial and Example Code

How to Count Files in a PHP Directory: Complete Tutorial and Example Code

gitbox 2025-07-29

Counting Files in a PHP Directory

In PHP, counting the number of files in a directory is a common task, especially when managing files and statistics. This article will show you how to accomplish this using built-in PHP functions.

Using scandir() Function to Read Directory Contents

We can use PHP's scandir() function to read all files and subdirectories in a specified directory. The function returns an array containing all items in the directory (including files and subdirectories).

Example code:

$arr = scandir($dir)

In the above code, $dir is the directory path to be read. The scandir() function returns an array of all files and subdirectories in the specified directory.

Filtering Out Directories

Since the scandir() function returns all items in the directory (including the current directory . and the parent directory ..), we need to filter these out using the array_diff() function.

Example code:

$files = array_diff($arr, ['.','..'])

In this code, the array_diff() function removes the current directory and parent directory items from the $arr array, leaving only the files in the directory.

Counting the Number of Files

Finally, we can use the count() function to count the number of files remaining in the array.

Example code:

$num_files = count($files)

By calling the count() function, we get the number of actual files in the directory.

Complete Example Code

Here is the full example code that demonstrates how to count the number of files in a directory using PHP:

$dir = '/path/to/php/directory';
$arr = scandir($dir);
$files = array_diff($arr, ['.','..']);
$num_files = count($files);
echo 'There are '.$num_files.' files in '.$dir.' directory';

Output

When you run this script, you will see output similar to the following:

<span class="fun">There are 54 files in /path/to/php/directory directory</span>

Conclusion

By using the scandir() and count() functions, we can easily count the number of files in a PHP directory. This method is very useful when working with file management and directory statistics in PHP.