Search code examples
phpsortingarray-multisort

php sort an array by value and for equal values, sort by key


I have an array

(0=>0,1=>3,2=>3)

I have to sort this array first by values, and for equal values , I have to sort by order of increasing key first.

I have tried to use multisort over the array_keys(SORT_DESC) and array_values(SORT_ASC) separately, but that gives me:

(0=>0,1=>3,2=>3)

but I want

(0=>0,2=>3,1=>3)

Solution

  • You can always use simple callback to sort it. Using uksort() it will be:

    $input = array(0 => 0, 2 => 3, 1 => 3);
    
    uksort($input, function($x, $y) use ($input)
    {
       if($input[$x]==$input[$y])
       {
          return $x<$y?-1:$x!=$y;
       }
       return $input[$x]-$input[$y];
    });