user541597
user541597

Reputation: 4355

Sorting directory files by creation date in php

Here is the code I use to get an array of the files in a directory.

$dir = "thumbnails/";
$images = scandir($dir);

How can I sort the $images array by creation date? I found a couple of ways but I couldn't get any of them to work with my array.

Thanks,

Upvotes: 1

Views: 3249

Answers (3)

Saulo Vallory
Saulo Vallory

Reputation: 979

You have to sort manually

$dir = "thumbnails/";

function compare_time($a, $b)
{
    global $dir;

    $timeA = filectime("$dir/$a");
    $timeB = filectime("$dir/$b");

    if($timeA == $timeB) return 0;

    return ($timeA < $timeB) ? -1 : 1;
}

$images = scandir($dir);
usort($images, 'compare_time');

Upvotes: 0

COLD TOLD
COLD TOLD

Reputation: 13599

try the following tutorial that includes a script on how to sort by file modification/creation.

http://www.bitrepository.com/sort-files-by-filemtime.html

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

On Windows you can get the creation time of the file with filectime(). Just put it in an array with the filename and sort the array.

Creation time is not stored on most *nix filesystems.

Upvotes: 1

Related Questions