Get latest X files generated from directory (PHP)

Im using this code to get the most recently generated file:

<?php 

    $files = glob($siteRoot.'/dir/*/*.php');
    $files = array_combine($files, array_map('filectime', $files));
    arsort($files);
    echo key($files); 

?>

      

How can I improve this to get the last 3 files created or what do I need? Any help would be greatly appreciated. Thank!

+3


source to share


2 answers


This should work for you:

Just take array_slice()

from your array:



$slice = array_slice($files, 0, 3); 

      

+3


source


To go with @ Rizier123's excellent answer, you don't need to change the array to sort it:



$files = glob($siteRoot.'/dir/*/*.php');
array_multisort(array_map('filectime', $files), SORT_DESC, $files);
$newest = array_slice($files, 0, 3);

      

+2


source







All Articles