homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

modifying the script to find the latest 5 folders

 3:09 pm on Apr 26, 2012 (gmt 0)

Hey everyone. I have this script which works fine for displaying all the subfolders in a folder.

I'd like to change it as to only display the 5 most recent. The script already displays the most recent at the top, so its just a case of limiting the results to 5.

$files = array();
$files_directory = "gallery";
$fdirectory = opendir("$files_directory");
while (false!==($file=readdir($fdirectory))) {
if (($file != ".") && ($file != ".." ) && ($file != "index.php~" ) && ($file != "index.php" )) {

$files[$file] = filemtime("$files_directory/$file");

while(list($key, $val)=each($files))

echo "<a href=\"$files_directory/$key/\">$key</a>";


I'm sorta familiar with $i++ and counting functions of PHP, but not enough to work it into the script and to make it work the way I'd like to.

Thanks :)



 3:45 pm on Apr 26, 2012 (gmt 0)

I've actually solved it. I hope :) It seems to work.
For some reason, this actually displays 5 folders..even though its set as to be less than or equal to 4.

$i = 0;
while((list($key, $val)=each($files)) && ($i <= 4))

echo "<a href=\"$files_directory/$key/\">$key</a>";



 4:06 pm on Apr 26, 2012 (gmt 0)

This is true of any language, not just PHP. You start at zero,
$i = 0;

does it - increments to 1.
does it - increments to 2.
See where it's going? When it gets to 4, it's actually done it 5 times, but $i is still 4.

This gets important with list arrays. count($myarray) may give you 5 elements, but the last element is still $myarray[4] because it's zero-based.

$myarray = array ('foo 1','foo 2','foo 3','foo 4','foo 5');

for ($i=0; $i < count($myarray); $i++) {
echo "$i " . $myarray[$i] . "<br>";

0 foo 1
1 foo 2
2 foo 3
3 foo 4
4 foo 5


 4:23 pm on Apr 26, 2012 (gmt 0)

Ah yes, didn't think of that. I suppose it was the equal to or less than that threw me a bit, rather than just a straight equal to.

But it makes sense (in a programming kinda way) ;)

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved