[SOLVED] PHP:: Double sort an array by priority

Issue

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)

Solution

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
)

Answered By – WOUNDEDStevenJones

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.