Sri Ni
Sri Ni

Reputation: 19

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?

Upvotes: 0

Views: 48

Answers (3)

Davinder Kumar
Davinder Kumar

Reputation: 662

You can use uasort for this.

$array = array('d' => 5, 'e' => 1, 'a' => 3, 'b' => 3, 'c' => 3, 'f' => 3);
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}
uasort($array, 'cmp');
print_r($array);

I tested the code and surely it will work for you.

Upvotes: 0

prava
prava

Reputation: 3986

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 !!!

Upvotes: 2

navaskhan
navaskhan

Reputation: 3

you can work like this its working.

    <?php
    $array1 = array( "[d]" => 5,"[e]" => 1,"[a]" => 3,"[b]" => 3,"[c]" => 3,"[f]" => 3 );
    $a = arsort($array1);
    foreach($array1 as $x => $x_value) {
        echo "Key=" . $x . ", Value=" . $x_value;
        echo "<br>";
    }
    ?>
output:
Key=[d], Value=5
Key=[f], Value=3
Key=[c], Value=3
Key=[a], Value=3
Key=[b], Value=3
Key=[e], Value=1

Upvotes: 0

Related Questions