skip to Main Content

Consider this simple example array:

$letters = [
    ['a', 'c', 'f'],
    ['c', 'f'],
    ['b', 'd', 'x', 'c', 'f'],
    ['f']
];

I need to order the array in descending order by number of letters (or anyway, by the number of elements in each array item:

'b', 'd', 'x', 'c', 'f'
'a', 'c', 'f'
'c', 'f'
'f'

2

Answers


  1. This should give you the result you are looking for:

    $letters = [
        ['a', 'c', 'f'],
        ['c', 'f'],
        ['b', 'd', 'x', 'c', 'f'],
        ['f']
    ];
    
    usort($letters, 'order');
    
    function order($a, $b){
        return (count($a) < count($b) ? 1 : -1);
    }
    
    var_dump($letters);
    
    Login or Signup to reply.
  2. The same in ‘2023 style’ ๐Ÿ˜Š

    usort($letters, fn ($a, $b) => count($b) <=> count($a));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search