switz
switz

Reputation: 25188

filter scandir and sort by date created

  1. I need to get the files in a directory in an array.
    • Only files that end in .markdown
  2. The files should be sorted by date created

Efficiency is not a huge deal, but I always like to make things as efficient as possible. There will be multiple directories with up to a couple hundred files in each.

I know I use the scandir function to get the files into an array, but I'm not sure where to go from there. I could throw it in a loop to check if the files end in .markdown, but is there some sort of regex I could pass in to the scan?

Thanks

Upvotes: 3

Views: 7372

Answers (2)

user142162
user142162

Reputation:

You can use glob() to get an array of filenames then use usort() and filectime() to order them by their creation dates:

$files = glob('*.markdown');
usort($files, function($file_1, $file_2)
{
    $file_1 = filectime($file_1);
    $file_2 = filectime($file_2);
    if($file_1 == $file_2)
    {
        return 0;
    }
    return $file_1 < $file_2 ? 1 : -1;
});

For PHP versions lower than 5.3:

function sortByCreationTime($file_1, $file_2)
{
    $file_1 = filectime($file_1);
    $file_2 = filectime($file_2);
    if($file_1 == $file_2)
    {
        return 0;
    }
    return $file_1 < $file_2 ? 1 : -1;
}

$files = glob('*.markdown');
usort($files, 'sortByCreationTime');

Upvotes: 9

Marc B
Marc B

Reputation: 360602

Easiest way to get the file list is simply do

$files = glob('*.markdown');

glob() basically does the same kind of wildcard matching that occurs at a shell prompt.

Sorting by date will require you to look at each of those files with stat() and retrieve its mtime/ctime/atime values (which fileatime(), filemtime(), filectime() return directly, but still use stat() internally).

Upvotes: 0

Related Questions