This is a modification of @Hugo Delsing's answer.
I needed to be able to group my brands together like this, but one bug in the code was the fact that if I had say iForce Nutrition and Inner Armour it would group these into two separate groups because of the letter case.
Changes I Made
Because it was fully alphabetical, it was only going by first letter I changes SORT_STRING to SORT_NATURAL
Changed: if ($char !== $lastChar) to if (strtolower($char) !== strtolower($lastChar))
<?php
$records = ['FinaFlex', 'iForce Nutrition', 'Inner Armour', 'Dymatize', 'Ultimate Nutrition'];
$lastChar = '';
sort($records, SORT_NATURAL | SORT_FLAG_CASE); //Allows for a full comparison and will alphabetize correctly.
foreach($records as $val) {
$char = $val[0]; //first char
if (strtolower($char) !== strtolower($lastChar)) {
if ($lastChar !== '')
echo '<br>';
echo strtoupper($char).'<br>'; //print A / B / C etc
$lastChar = $char;
}
echo $val.'<br>';
}
?>
The final output will be like this
D
Dymatize
F
FinaFlex
I
iForce Nutrition
Inner Armour
U
Ultimate Nutrition
I hope this helps everyone, and a big thank you to Hugo for providing the code that got me exactly where I needed to be.
You can see my example here https://hyperionsupps.com/brand-index