phparrayssortingstable-sort

arsort() doesn't provide a stable sort for elements with the same value


I want to sort an array in reverse order of values. I used arsort php function but the result is not good for me.

Example:

I want to sort next array:

$myArray = array("d" => 1, "f" => 2, "b" => 3, "c" => 4,  "e" => 2); 

after using arsort(), the result is:

$myArray = array ( "c" => 4, "b" => 3, "e" => 2, "f" => 2, "d" => 1 );

which it is not good because the arsort function doesn't keep initial order of elements in array.

I want the result like:

$myArray = array ( "c" => 4, "b" => 3, "f" => 2, "e" => 2, "d" => 1 );

f before e order, like from original array. keys with same value to not reverse.


Solution

  • Edit: This isn't doable with a built in function and you need to implement your own sorting solution. You can follow this question I opened to understand more.


    It is a coincidence that these solutions work:

    $myArray = array("d" => 1, "f" => 2, "b" => 3, "c" => 4,  "e" => 2);
    uasort($myArray, function($a, $b){
        if($a == $b)
            return 1;
        else
            return $b - $a;
    });
    print_r($myArray);
    

    or

    $myArray = array("d" => 1, "f" => 2, "b" => 3, "c" => 4,  "e" => 2);
    uasort($myArray, function($a, $b){
        return $a <= $b;
    });
    print_r($myArray);