Search code examples
phpfilesortingdir

Php sort file from dir in desending order (Latest at top)


**Files by date descending order, How to do it? ** Need to show Files by date latest at top

function list_dir($dn){
    if($dn[strlen($dn)-1] != '\\') $dn.='\\';
    static $ra = array();
    $handle = opendir($dn);
    while($fn = readdir($handle)){
        if($fn == '.' || $fn == '..') continue;
        if(is_dir($dn.$fn)) list_dir($dn.$fn.'\\');
        else $ra[] = $dn.$fn;
    }
    closedir($handle);
    return $ra;
} 
 $filelist = list_dir('D:\xampp\htdocs');
    for($i=0;$i<count($filelist);$i++){
        $test = Array();
        $year = $test[2];
        $day = $test[1];
        $month = $test[0];       
        $test = explode("/",date("m/d/Y",filemtime($filelist[$i])));
        echo "<span style='color:red;'><b  style='color:green;'>".$day.'-'.month.'-'.$year. '</b> ' . $filelist[$i]."</span><br>";
    }
 clearstatcache();

Solution

  • You can use glob, then arsort to sort from high to low.

    $files = glob("*"); //Fetch all files.
    $files = array_combine($files, array_map("filemtime", $files)); //Grab the filetime for each file
    arsort($files); //Sort high to low
    echo "<pre>";
    echo print_r($files, true);
    echo "</pre>";
    

    Output (after formatting in a table)

    https://i.sstatic.net/1gm9b.png

    <?php
    
    $files = glob("*"); //Fetch all files.
    $files = array_combine($files, array_map("filemtime", $files));
    arsort($files);
    echo "<table>
           <tr>
             <th>File</th>
             <th>Last modified</th>";
    foreach( $files as $file => $date ) {
        echo '<tr><td>'. $file .'</td><td>'. date("Y m d g:i:s a", $date).'</td></tr>';
    }
    echo "</table>";