Files Only: PHP Quick Tip

In the last entry on the MegaGallery project, I suggested checking for directories in the file list as a way to improve the project. In this Quick Tip, I am going to show you a possible solution. This solution will work in any situation where you need a list of files only.

The Code

$file_list = scandir("./");

foreach ($file_list as $file) {
   if (filetype($file) == "file") {
      $files[] = $file;

We use scandir() to get a list of all the files and directories in the specified directory. We use a foreach loop to iterate through the array $file_list. Using the function filetype(), we check to see if the current element is a file. If it is, we add it to a new array named $files. We now have an array ($files) that contains only files and no directories.

That’s it for this Quick Tip. I hope you find it useful.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s