Search code examples
phparraysscandir

Scandir newest files in array with limit


I have made a PHP script to scan a directory, it lists all filenames in an array with a limit of 20. Now its displaying only the beginning of the array. So if there are 40 files, it displays only the first 0-20 but we need 20-40.. Can someone help me ? Thanks!!

<?php

$files = glob('data/*.{png}', GLOB_BRACE);
usort($files, 'filemtime_compare');

function filemtime_compare($a, $b)
{
    return filemtime($a) - filemtime($b);
}

$i = 0;
$show = 20;
foreach($files as $file)
{
    if($i == $show) {
         break;
    } else {
         ++$i;
    }
    $var .= $file . "\n";

}
$fp = fopen("data.txt", "wb");
fwrite($fp, $var);  
fclose($fp);
echo $var;

?>

Solution

  • You could use array_chunk() to split the $files array up in chunks of 20 files. Then use implode() to format the values in a chunk to a single string. Replace the foreach loop with this:

    $show = 20;
    $files = array_chunk($files, $show);
    $page = 0; // page 0 is 0-19, page 1 is 20-39, etc.
    $var = implode("\n", $files[$page]);
    

    Edit: For the last 20 files you could use array_slice():

    $files = array_slice($files, -20);
    $var = implode("\n", $files);