Search code examples
phpsortingfilemtime

Sort function works wrong with filemtime PHP


I'm trying to sort files by modification date using PHP.

I'm using filemtime function then sort function using the following code:

<?php

$array2 = array();
$images = glob("*.*");
foreach($images as $image) {
echo "Last modified: ".date("F d Y H:i:s.",filemtime($image));
echo "<br>";

array_push($array2,date("F d Y H:i:s.",filemtime($image)));
}
//echo array2;
sort($array2);
echo "<br>";

foreach ($array2 as $ar)
{
    echo $ar;
    echo "<br>";

}
//$array2[$image] = date("F d Y H:i:s.",filemtime($image));

?>

and the output is like this

Last modified: June 21 2013 15:48:42.
Last modified: June 12 2013 14:43:10.
Last modified: April 09 2013 15:39:13.
Last modified: June 12 2013 14:00:14.
Last modified: June 21 2013 16:08:58.
Last modified: July 15 2013 12:44:28.
Last modified: July 15 2013 12:48:48.
Last modified: July 15 2013 14:42:19.
Last modified: July 15 2013 14:54:48.
Last modified: April 09 2013 15:39:13.
Last modified: June 21 2013 15:34:30.
Last modified: June 21 2013 15:56:32.

April 09 2013 15:39:13.
April 09 2013 15:39:13.
July 15 2013 12:44:28.
July 15 2013 12:48:48.
July 15 2013 14:42:19.
July 15 2013 14:54:48.
June 12 2013 14:00:14.
June 12 2013 14:43:10.
June 21 2013 15:34:30.
June 21 2013 15:48:42.
June 21 2013 15:56:32.
June 21 2013 16:08:58.

here you can see July is between April and June

can anyone please guide me to the problem ?


Solution

  • The problem is that you are sorting the human-readable representations of the dates, so obviously April comes first (it starts with A).

    What you need to do is something like

    foreach($images as $image) {
        array_push($array2, filemtime($image));
    }
    
    sort($array2);
    
    // and now, AFTER sorting get the formatted dates 
    foreach ($array2 as $ts)
    {
        echo date("F d Y H:i:s.", $ts);
    }
    

    Some tips:

    1. You can get the last modified times for your files in just one line with

      $array2 = array_map('filemtime', $images);
      
    2. date depends on the system timezone. Make sure you have set it properly with date_default_timezone_set before doing anything.