8

Currently, I have my array sorting by string length. But, when the string lengths are equal, how do I sort by value?

As an example, my current code:

$array = array("A","BC","AA","C","BB", "B");

function lensort($a,$b){
    return strlen($a)-strlen($b);
}

usort($array,'lensort');

print_r($array);

Outputs:

Array
(
    [0] => C
    [1] => A
    [2] => B
    [3] => BB
    [4] => AA
    [5] => BC
)

But, I'd like it to sort by the following instead:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)

2 Answers 2

11

Incorporate both checks into your comparator:

function lensort($a,$b){
    $la = strlen( $a); $lb = strlen( $b);
    if( $la == $lb) {
        return strcmp( $a, $b);
    }
    return $la - $lb;
}

You can see from this demo that this prints:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)
Sign up to request clarification or add additional context in comments.

Comments

0

Here is another method:

$f = function ($s1, $s2) {
   $n = strlen($s1) <=> strlen($s2);
   if ($n != 0) {
      return $n;
   }
   return $s1 <=> $s2;
};
usort($array, $f);

https://php.net/language.operators.comparison

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.