John Doe
John Doe

Reputation: 3691

How can I glob a directory, sort the files by time/date, and print the names of the files in order?

I'm looking for a way to glob a directory and sort the contents by time/date and print it on the PHP page. There must be a way to do this, I've tried the following code but it won't print anything out on the page:

<?php
$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
?>

print_r wont work because I need just the file name. I'm new to PHP arrays so I need as much help as I can get!

Upvotes: 2

Views: 1503

Answers (2)

salathe
salathe

Reputation: 51970

Given your original code:

$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);

From there you could either loop on the array of sorted filename/mtime pairs, or create a new array with just the filenames (in their sorted order).

The first looks like:

foreach ($files as $file => $mtime) {
    echo $file . " ";
}

The second could be:

foreach (array_keys($files) as $file) {
    echo $file . " ";
}

Depending on your needs, it might also be okay to simply:

echo implode(" ", array_keys($files));

Upvotes: 2

Shad
Shad

Reputation: 15471

Sounds like you're looking for foreach

foreach($files as $filename=>$mtime){
    echo AS INTENDED;
}

Upvotes: 0

Related Questions