Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glob() - sort array of files by last modified datetime stamp

I'm trying to display an array of files in order of date (last modified).

I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?

like image 849
cole Avatar asked Sep 24 '08 01:09

cole


4 Answers

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is:

<?php

$myarray = glob("*.*");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));

?>

Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.

like image 176
Jay Avatar answered Nov 15 '22 06:11

Jay


<?php
$items = glob('*', GLOB_NOSORT);
array_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items);
like image 45
Alf Eaton Avatar answered Nov 15 '22 07:11

Alf Eaton


This solution is same as accepted answer, updated with anonymous function1:

$myarray = glob("*.*");

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

1Anonymous functions have been introduced in PHP in 2010. Original answer is dated 2008.

like image 35
fusion3k Avatar answered Nov 15 '22 06:11

fusion3k


Since PHP 7.4 the best solution is to use custom sort with arrow function:

usort($myarray, fn($a, $b) => filemtime($a) - filemtime($b));

You can also use the spaceship operator which works for all kinds of comparisons and not just on integer ones. It won't make any difference in this case, but it's a good practice to use it in all sorting operations.

usort($myarray, fn($a, $b) => filemtime($a) <=> filemtime($b));

If you want to sort in reversed order you can negate the condition:

usort($myarray, fn($a, $b) => -(filemtime($a) - filemtime($b)));
// or 
usort($myarray, fn($a, $b) => -(filemtime($a) <=> filemtime($b)));

Note that calling filemtime() repetitively is bad for performance. Please apply memoization to improve the performance.

like image 7
Dharman Avatar answered Nov 15 '22 07:11

Dharman