homepage Welcome to WebmasterWorld Guest from 107.21.163.227
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Pubcon Website
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
surrealillusions




msg:4446028
 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");
}
}
closedir($fdirectory);
clearstatcache();
arsort($files);

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 :)

 

surrealillusions




msg:4446051
 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>";
$i++;

}

rocknbil




msg:4446062
 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

surrealillusions




msg:4446070
 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.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved