If I have these files in a directory: 13.php 17.php 210.php How can I make a loop that will list them in numerical order? I know how to make a while loop, but not to take a numerical filename into account.
ie: <?php if ($handle = opendir('websites')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $entry = str_replace('.php','', $entry); echo '<a href="http://'.$entry.'" target="_blank">'.$entry.'</a><br />'; } } closedir($handle); } ?> Code (markup): How can I get the above code to display the files in numerical order?
I would glob the files into an array... since Glob automatically sorts by filename. As such those numbered names would be auto-sorted. <?php foreach (glob('websites/*.php') as $siteFile) { $entry=pathInfo($siteFile,PATHINFO_BASENAME); echo '<a href="http://',$entry,'">',$entry,'</a><br />'; } ?> [code] Though be warned you may end up having to build a usort it if you want 12 listed after 9, since you're not using leading zero's. This is probably why Eric linked you to the sort routines as in that case you would want to glob it in unsorted, then run a usort on it. P.S. This is 2013, not 1997... as such you shouldn't be using TARGET since that pisses on accessibility by not giving the user the choice of if it's in a new window or not... and comma delimits are a fraction faster than string addition and less prone to problems on echo, since it sends each section as it's built instead of having to build the new string before sending -- just saying. Code (markup):
I was going to help, but this was really rude so I decided not to help. He gives you most of the answer and you insult him.
Something like this should work: <?php if ($handle = opendir('websites')) { $data = array(); while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $data[] = str_replace('.php','', $entry); } } closedir($handle); natsort($data); foreach ($data as $entry) { echo '<a href="http://'.$entry.'" target="_blank">'.$entry.'</a><br />'; } } PHP: