Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Php order array by number of elements

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading