Andrea php Andrea php - 4 months ago 8
PHP Question

Get the last X number of files in a directory

How can I get the last X number of files in a directory in PHP?

I use this code for getting the last file, but how I can get the last X number of files?

My code:

$path = "/path/test/";

$latest_ctime = 0;
$latest_filename = '';

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}

Answer
<?php
$arr = array();
$path = "/Users/alokrajiv/Downloads/";
$d = dir($path);
if ($handle = opendir($path)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $filepath = "{$path}{$entry}";
            $tmp = array();
            $tmp[0] = $filepath;
            $tmp[1] = filemtime($tmp[0]);
            array_push($arr, $tmp);
        }
    }
    closedir($handle);
}
function cmp($a, $b){
    $x = $a[1];
    $y = $b[1];
    if ($x == $y) {
        return 0;
    }
    return ($x > $y) ? -1 : 1;
}
usort($arr, 'cmp');
$x = 10;
while(count($arr)>$x){
    array_pop($arr);
}
var_dump($arr); //has last modified 10 files

Sort in the descending order then pop till 10 elements are left.

Comments