# [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 (  => i  => an  => am  => 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
(
 => i
 => aa
 => am
 => an
 => az
 => ba
 => by
 => alien
)
``````