-1

Given I have an array

['test', 'te', 'tes', 'z'];

And use PHP sort() function, I get the following result

Array ( [0] => te [1] => tes [2] => test [3] => z )

But what I am trying to achieve is this

 ['test', 'tes', 'te',  'z'];

I have looked through the documention of the sort functions and couldn't find the right sort flag to achieve it.

fabla
  • 1,806
  • 1
  • 8
  • 20

1 Answers1

0

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;
});
Progrock
  • 7,373
  • 1
  • 19
  • 25