How to count the number of files in a directory in PHP?

To count the number of files in a directory in PHP, you can use the scandir() function to retrieve an array of all files and directories in the given directory. Then, you can use a loop to iterate through the array and count only the files present in it.

Here's an example:

$directory = '/path/to/directory'; // Replace with the path to your directory $files = scandir($directory); $count = 0; foreach ($files as $file) { if (is_file($directory . '/' . $file)) { $count++; } } echo 'Number of files in directory: ' . $count;

In this example, $directory is the path to the directory you want to count the files in. The scandir() function is used to retrieve an array of all files and directories within the specified directory. Then, a loop iterates through each item in the array using the $file variable. If is_file() returns true for an item, it means it is a file and it is counted incrementing the $count variable. Finally, the result is displayed using echo.