Search code examples
phpreferenceserver-side

How to order filenames on last modified date glob PHP


I've got this code:

<?php 
  foreach (glob("*files/*.html") as $filename) { 
  echo "<iframe src=$filename></iframe>"; 
} 
?>

The structure is like this:

|-index.php
|-files 
   |- are.html
   |- hello.html
   |- who.html
   |- you.html

The problem is: it isn't sorted on date. I tried it with filemtime (http://php.net/manual/en/function.filemtime.php) with this code:

<?php 
  foreach (glob("*files/*.html") as $filename) { 
  echo "<iframe src=$filename></iframe>"; 
}
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?> 

but it only echoes 1 of the 4 html's I got in that directory: you.html How can I let it echo all 4 html's on last modified date?


Solution

  • This works :)

    $myFiles = glob("*files/*.html");
    usort($myFiles, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
    
    foreach ($myFiles as $filename) { 
    echo "<iframe src=$filename></iframe>"; 
    }