Page 1 of 1
Count files display only 3 or less
Posted: Tue Jun 01, 2010 10:20 pm
by curtranhome
Hey, I was wondering if there was a way to get php to count the amount of files in a directory, then display only 3 of those files, in my case, the newest ones. How would one go by doing this? I have tried the count() method inside of a while loop, is that the wrong angle to take?
Re: Count files display only 3 or less
Posted: Tue Jun 01, 2010 11:08 pm
by requinix
Unless you need it recursively, use
glob to get an array of files, and
shuffle if you want to choose three random files.
Re: Count files display only 3 or less
Posted: Tue Jun 01, 2010 11:13 pm
by curtranhome
ok, well thanks, but I am using glob and count to get the files and the number of files. What I am trying to do is get an admin to post a news entry, then have a php script on the index page to count 3 of the newest entries (names are the entry date) and display them in a div tag. Got any ideas?
Re: Count files display only 3 or less
Posted: Wed Jun 02, 2010 12:02 am
by requinix
Use a database.
Otherwise you'll have to get the list of all files and sort by file modification time. Lots of file system hits.
Re: Count files display only 3 or less
Posted: Wed Jun 02, 2010 12:07 am
by curtranhome
Thats would do it, but my web server is
not database compatible, so file systems is all I got.

So how would I do that with filesystems?
Re: Count files display only 3 or less
Posted: Fri Jun 11, 2010 10:21 am
by curtranhome
Is this even possible, or is it taking it a long time to look up?
Re: Count files display only 3 or less
Posted: Fri Jun 11, 2010 3:07 pm
by lunarnet76
raw rapid version :
<?php
$list=array();
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
$list[]=$file;
}
closedir($handle);
}
$results=array_rand($list,3);
?>
and you will have your 3 files in the $results
Re: Count files display only 3 or less
Posted: Sat Jun 12, 2010 11:45 am
by Jonah Bron
This code will get the three newest ones, instead of randomly selecting them.
Code: Select all
$top3 = array(array(null,0), array(null,0), array(null,0));
foreach ($list as $item) {
$m = filectime('path/to/file/'.$item);
if ($m < $top3[0][1]) {
$top3[2] = $top3[1];
$top3[1] = $top3[0];
$top3[0] = array($item, $m);
} elseif ($m < $top3[1][1]) {
$top3[2] = $top3[1];
$top3[1] = array($item, $m);
} elseif ($m < $top3[2][1]) {
$top3[2] = array($item, $m);
}
}
Just replace $results=array_rand($list,3); in lunarnet76's code with this code.
Re: Count files display only 3 or less
Posted: Tue Jun 29, 2010 9:13 pm
by curtranhome
Hey, thanks for all the replies but none of them work for me.... is there another way? maybe the php count() function??
