tags:

views:

35

answers:

3

I have the code below that outputs the names of files in a directory. I'd like to separate the file names alphabetically by an additional line space when the first letter of the file changes (say from A to B). Any ideas? Thanks.

            $dirs = scandir("Dir");
            foreach($dirs as $file)
            {
                    if (($file == '.')||($file == '..'))
                    {
                    }
                    elseif (is_dir($tdir.'/'.$file))
                    {
                            filesInDir($tdir.'/'.$file);
                    }
                    else
                    {
                            echo $file."<br>";
                    }
            }
+2  A: 

You can just monitor the first character of each file name. You can access individual characters of a string using array syntax, such as $string[0] for the first character:

        $dirs = scandir("Dir");
        $char = null;
        foreach($dirs as $file)
        {
                if (($file == '.')||($file == '..'))
                {
                }
                elseif (is_dir($tdir.'/'.$file))
                {
                        filesInDir($tdir.'/'.$file);
                }
                else
                {
                        if ($file[0] != $char && $char !== null) echo "<br>";
                        echo $file."<br>";
                        $char = $file[0];
                }
        }
zombat
A: 
Joel Alejandro
A: 

Kind of a hack, BUT if your on *nix:

ls -al |  awk '{print $9}'

Will give you back the directories contents in alphabetical order.

Mr-sk