Search code examples
phparrayssortingstable-sort

arsort() is not preserving the original element order for duplicated values (below PHP8)


Below is an output of my array

$array1 = Array (
    [d] => 5
    [e] => 1
    [a] => 3
    [b] => 3
    [c] => 3
    [f] => 3
)

I want to sort it like...

Array (
    [d] => 5
    [a] => 3
    [b] => 3
    [c] => 3
    [f] => 3
    [e] => 1
)

I am using arsort($array1)

which results in var_dump($array1)

array (size=6)
'd' => int 5
'f' => int 3
'c' => int 3
'a' => int 3
'b' => int 3
'e' => int 1

anyways to fix this?


Solution

  • Try this :

    $array1 = [
        'd' => 5,
        'e' => 1,
        'a' => 3,
        'b' => 3,
        'c' => 3,
        'f' => 3
    ];
    
    array_multisort(array_values($array1), SORT_DESC, array_keys($array1), SORT_ASC, $array1);
    
    print_r($array1);
    

    Here first array_values($array1), SORT_DESC will sort the values in descending order and then array_keys($array1), SORT_ASC will sort the keys into ascending order and finally both the thing applies to the main array i.e. $array1.

    O/P - Array ( [d] => 5 [a] => 3 [b] => 3 [c] => 3 [f] => 3 [e] => 1 ) 
    

    I hope this time I get what you want. Finger crossed !!!