I have an array that already contains all it\'s values in alphabetical order:
Alligator
Alpha
Bear
Bees
Banana
Cat
Cougar
Now I just want to li
The solution is to keep in a variable the first letter of the previously printed word, like:
$previous = null;
foreach($array as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
$previous = $firstLetter;
echo $value."\n";
}
NB: if some entries start with a lower-case letter and others with upper-case letters, use the strcasecmp
function in the test instead of !==
.