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)
You're missing the logic to account for sorting by character value. You can add that logic into your custom sort method:
You can combine this into a single line by using a ternary:
Full example (https://3v4l.org/msISD):
outputs: