Dave
Dave

Reputation: 26

Limit Max Results after glob sort by time

I'd like to limit the results returned after I glob the files in a directory and sort them by time. And just in case there are no files in the directory, I'd like to include an if file exists phrase as well. Here is the code so far.

$list = glob('items/*.html');
usort(
   $list,
   create_function('$a,$b', 'return filemtime($a) < filemtime($b);')
);


foreach($list as $file)
{
    include $file;
}

Now I'm guessing, I can probably do the if (file_exists()) part like this:

foreach($list as $file)
{
 if (file_exists($file)) {
    include $file;}
}

part without throwing errors, but where do I do the count up to a max of 5 or 7?

Upvotes: 1

Views: 1132

Answers (3)

kapa
kapa

Reputation: 78741

$limit=5;
$list = glob('items/*.html');
usort(
   $list,
   create_function('$a,$b', 'return filemtime($a) < filemtime($b);')
);  

$list=array_slice($list, 0, $limit);

foreach($list as $file) {
    include $file;
}

There is not really a need to do a file_exists() query here, because if glob found it, it should exist. You might want to do an is_readable() though, in this case you could rewrite it like this:

$limit=5;
$list = glob('items/*.html');
usort(
   $list,
   create_function('$a,$b', 'return filemtime($a) < filemtime($b);')
);  

$i=0;    
foreach($list as $file) {
    if ($i < $limit && is_readable($file)) {
         include $file;
         $i++;
    }
}

You might also want to add a check if glob failed for some reason.

$list = glob('items/*.html');
if ($list===false) {
    /*handle error (or simply $list=array() if you don't care)*/
}

Upvotes: 1

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14951

glob returns an empty array when there are no files in the directory. This means, that an file_exists would be useless, as if you have an value from glob, it would exist.

If glob somehow fails, it will return false. You're script will throw some errors if this happens. Try checking for an array before the foreach using is_array.

Upvotes: 1

xkeshav
xkeshav

Reputation: 54072

try ( for max 5 file to include )

foreach($list as $k=>$v)
{
  if($k<5 && file_exists($v))
    include_once $file;
  else
      break;

}

Upvotes: 0

Related Questions