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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.