Sort the list, then build a new array with keys as the first character and value as a list of words beginning with that character. Then reverse sort those word lists and merge the array again.
<?php
$items = [
'foolhardy',
'foo',
'foolish',
'fool',
'football',
'footbridge',
'apple'
];
sort($items);
var_export($items);
foreach($items as $item) {
$tmp[$item[0]][] = $item;
}
foreach($tmp as &$v) {
rsort($v);
}
$out = array_merge(...array_values($tmp));
var_export($out);
Output:
array (
0 => 'apple',
1 => 'foo',
2 => 'fool',
3 => 'foolhardy',
4 => 'foolish',
5 => 'football',
6 => 'footbridge',
)array (
0 => 'apple',
1 => 'footbridge',
2 => 'football',
3 => 'foolish',
4 => 'foolhardy',
5 => 'fool',
6 => 'foo',
)
Alternatively, you can do this with usort and the spaceship comparison operator. Compare items, if they begin with the same letter reverse sort, else sort alphabetically:
<?php
usort($items, function($a, $b) {
return
$a[0] === $b[0]
? $b <=> $a
: $a <=> $b;
});