readdir组文件夹的第一个字母

I have a list of folders but want to group them by first letter ie all A folders together, all B folder together etc:

$handle = opendir(".");
$projectContents = '';
while ($file = readdir($handle)) 
{
    if (is_dir($file) && !in_array($file,$projectsListIgnore)) 
    {

$projectContents .= '<li><a href="'.$file.'">'.$file.'</a></li>';

    }
}
closedir($handle);

Output:

<ul>
 $projectContents
</ul>

The above snippet lists them fine from a-2-z but I don't know how to section them off into groups.

The closing and re-opening of </ul><ul> with each new letter section would be enough but again don't kow how to impliment into the current snippet.

Compare the first character of the current file name in the loop with the first character of the previous one, then print the </ul><ul> if they're not the same:

$handle = opendir(".");
$projectContents = '';
$firstLetter = '';
while ($file = readdir($handle)) 
{
    if (is_dir($file) && !in_array($file,$projectsListIgnore)) 
    {
        if ($firstLetter != strtoupper($file{0}) && $firstLetter != '')
        {
            $projectContents .= '</ul><ul>';
        }
        $firstLetter = strtoupper($file{0}); // Store the current character for comparison
        $projectContents .= '<li><a href="'.$file.'">'.$file.'</a></li>';

    }
}
closedir($handle);

I would first store all the directories names in an array and than use asort() function to sort all the items alphabetically, and than do the link creation.