1

i want preg_match to find all files in a given directory and display them on a page. I know how to do that but how do i sort them by date of CREATION? I want the newest one on top. This is my code:

function find_files() {
 $files = scandir("content");
 foreach ($files as $value) {
  if(preg_match("/file/", $value)) {
    echo "<li>$value</li>";    
  } 
 }
}

Thank you.

EDIT: according to the answers i got i modified my code like this:

function find_files() {
 $files = scandir("content");
 usort($files, create_function('$a,$b', 'return filectime($a)<filectime($b);'));
 foreach ($files as $value) {
  if(preg_match("/file/", $value)) {
    echo "<li>$value</li>";    
  } 
 }
}

However it still wont work. The browser wont finish loading.

Cain Nuke
  • 1,865
  • 4
  • 29
  • 52
  • Use [`filectime()`](http://php.net/manual/en/function.filectime.php) to get the creation time. – Ja͢ck Nov 26 '14 at 06:46
  • As far as i know, that gets the last modified date, not the creation date. – Cain Nuke Nov 26 '14 at 07:10
  • That question is asking how to sort by LAST MODIFICATION date. I dont ened that but file CREATION date. 2 completely different things. – Cain Nuke Nov 27 '14 at 05:20
  • It's based on the same principle; just exchange `filemtime()` and `filectime()` and you're done. Also, read [this question](http://stackoverflow.com/a/4401374/1338292) about retrieving creation time of files. – Ja͢ck Nov 27 '14 at 05:23
  • Thanks for all your help but im still lost. I modified my question and added the new code i figured out by reading the data you provided but it wont work. – Cain Nuke Nov 27 '14 at 05:33

1 Answers1

1

PHP supports lots of ways to sort arrays, see how they work here. You could run it as asort($files).

The right way to solve this is by sorting the array prior to outputting it. Something along the lines of:

asort($files );
foreach($files as $value) {
  if (preg_match('/file/', $value))
    array[index++] = $value;
}
Sinsil Mathew
  • 498
  • 6
  • 20
  • Hmm, I just read about asort but seems like it only sorts alphabetically. – Cain Nuke Nov 26 '14 at 07:09
  • You use usort instead of asort.Please refer this link http://stackoverflow.com/questions/16733128/sort-array-by-date-in-descending-order-by-date-in-php – Sinsil Mathew Nov 26 '14 at 07:17