How to use glob() function to sort files from a directory?

Hello All,

How to use glob() function to sort files from a directory? Let say in “test” directory there are 10 files. I want to fetch files on basis of “Date modified”. Is it possible?

my code is :

foreach(glob(‘test/test*.xml’) as $file)
{
echo $file.“<br>”;
}

Umm! somehow this should help you:


$myarr = array();
foreach(glob('test/test*.xml') as $file){
	$myarr[$file] = filemtime($file);
}
print "<pre>";
print "====== before sort ==========";
print_r($myarr);
asort($myarr);
print "====== after sort ===========";
print_r($myarr);

I believe this will return the timestamp of the file, so to make it a little more readable/userfriendly you may wat to wrap the filemtime function within the date() function, like this:

$myarr = array();
foreach(glob('test/test*.xml') as $file){
$myarr[$file] = date ("F d Y H:i:s.", filemtime($file));
}

print "<pre>";
print "====== before sort ==========";
print_r($myarr);
asort($myarr);
print "====== after sort ===========";
print_r($myarr);

I assumed that OP has nothing to do with that date that’s why i did like that. I knew about that the filemtime() function just gives time stamp. And his actual goal is to sort the files with modified date. So if you format the date before sorting then that might not sort properly. The date can be formatted while displaying the filenames and dates later after sorting.

Thank you Webnoob and Rajug. Now i can sort files as per my requirement.

Good point, I didn’t think of that :slight_smile: