Blog

Saturday, November 25, 2006
sorted list of tags
OK, this time I've revised my PHP code to show a sorted list of labels:
<?php
$dirname = "."; # current directory
$dir = opendir($dirname);
$file_list = array();
$i = 0;

while (false != ($file = readdir($dir)))
{
if (ereg(".html$", $file))
{
$tag = substr($file, 0, strlen($file)-5);
$file_list[$i] = "<li><a href='/labels/$file'>$tag</a>";
$i++;
}
}
closedir($dir);
natcasesort($file_list);
?>
<h1>My Tags</h1>
<ul>
<?php foreach ($file_list as $file) echo($file); ?>
</ul>


Not a big deal, but it does show a (probably) typical use of arrays in PHP. As a side note, the "foreach" construct in PHP is a bit different from the usual foreach in other languages. It's usually something like "foreach (item in list)", while in PHP it's reversed: "foreach (list as item)". I should also mention that I first tried the regular sort() function, but switched to natcasesort(), since a case-insensitive sort makes more sense here.

Labels: ,

posted by Unknown 11:50 AM
0 comments

Comments: Post a Comment


This page is powered by Blogger. Isn't yours?
© 2011 Andrew Huey