You don't need the first foreach loop. It just repeatedly assigns the same variable $name. You can do this in the loop that echoes the DIVs.

You can get the first letter of a string with $name[0].

Rather than testing for $i == 3 to know when to close the UL and DIV, test for $i > 3 to skip printing the names. Otherwise, if a letter has only 1 or 2 names in its group, you'll never close the group.