Jump to content

[SOLVED] Limit the output from an array?


adx

Recommended Posts

Hey guys! My head must be screwed on backwards today.

I just need to list some files from a directory and output them as no more than

5 links, while sorting them by last modified.

 

This first one does just that but I can't figure out how to limit the number of links!

 

<?php
$files = glob("*.html");
array_multisort(array_map('filemtime', $files), SORT_DESC, $files);
foreach ($files as $filename) {
echo "<a href=\"".$filename."\">".$filename."</a><br />";}
?>

 

On this next one I can limit the amount of links but I can't get it to list by

last modified date..

 

<?php
$files = glob("*.html");
$file_array = array($files);
foreach ($file_array as $filename) {
echo nl2br("
<a href=\"".$filename[0]."\">".$filename[0]."</a>
<a href=\"".$filename[1]."\">".$filename[1]."</a>
<a href=\"".$filename[2]."\">".$filename[2]."</a>");}
?>

 

I suppose the golden answer is to merge these somehow, but alas, I can't

seem to wrap my head around it. I'm probably fried from all the nicotine that

went into this. So if you could assist a bit, it would be much appreciated!

Link to comment
https://forums.phpfreaks.com/topic/135396-solved-limit-the-output-from-an-array/
Share on other sites

Could you not just change the foreach loop in the first one to a for loop and count the first five for output?

 

<?php
$files = glob("*.html");
array_multisort(array_map('filemtime', $files), SORT_DESC, $files);
for ($i=0;$i<5; $i++) {
echo "<a href=\"".$files[$i]."\">".$files[$i]."</a><br />";}
?>

 

Sorry, brain freeze... knew you only wanted five, and still I put in less than array count on original post :)

 

That should work though

Don't know if this will work (not tested) but it should give you an idea of how to limit the links to 5.

 

 $x=0;
$files = glob("*.html");
array_multisort(array_map('filemtime', $files), SORT_DESC, $files);
foreach ($files as $filename) {
echo "".$filename."
";
$x++;
if($x==5) { break; }
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.