Skip to content
Advertisement

PHP:: Double sort an array by priority

My goal is to sort an array first by the string length and after that sort it again by character value without changing the priority of the length.

Here is my code:

$arr=array("an","am","alien","i");

usort($arr, function ($a, $b) { return (strlen($a) <=> strlen($b)); });

print_r($arr);

I am getting :

Array ( [0] => i [1] => an [2] => am [3] => alien )

…almost but not there)

Advertisement

Answer

You’re missing the logic to account for sorting by character value. You can add that logic into your custom sort method:

// if lengths are the same, then sort by value
if (strlen($a) == strlen($b)) {
    return $a <=> $b;
}
// otherwise, sort by length
return (strlen($a) <=> strlen($b));

You can combine this into a single line by using a ternary:

return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);

Full example (https://3v4l.org/msISD):

<?php

$arr=array("aa", "az", "an","am", "ba", "by", "alien","i");

usort($arr, function ($a, $b) {
    return strlen($a) == strlen($b) ? $a <=> $b : strlen($a) <=> strlen($b);
});

print_r($arr);

outputs:

Array
(
    [0] => i
    [1] => aa
    [2] => am
    [3] => an
    [4] => az
    [5] => ba
    [6] => by
    [7] => alien
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement