Search code examples
phpsortingpresentation

PHP-generated list of files sorted and separated by letter : lowercase-starting filenames are pushed to the bottom


I use this code to generate a list of files, in an index-forbidden-by-apache directory :

 <?php
// create array of letters of the aplhabet
$letters = array("a","b","c","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");    

foreach (glob("*.*") as $filename) {               
    if (in_array(strtolower($filename[0]),$letters)){ // check if first character of filename is in the array
        echo "<br />"; 

        if(($key = array_search(strtolower($filename[0]), $letters)) !== false) {
            unset($letters[$key]);  //remove letter from array
        }
    }

    echo "<a href='".$filename."'>".$filename."</a>&nbsp; &#8212;&#8212; &nbsp; ".intval(filesize($filename) / (1024 * 1024))."MB<br />";
}
                ?>

That generates a list of all the files, in groups based on the first letter. First, all the "A" letter. Skip a line. Then, all file names starting with B. Line skip. And so on.

However, the file names starting with a lowercase are all pushed, in a single group, at the bottom of the listing. And I just don't understand why (I did use strtolower, see) and how to fix it.

If you see how to fix it and have file names starting with a lower case character listed among the file names starting with a capital, thank you !


Solution

  • Use

    $files = glob("*.*");
    natcasesort($files);
    foreach ($files as $filename) { 
    

    Probably glob is returning the files sorted case sensitive. So sort the array first before processing.