PHP asort not working correctly?

I have an example array:

$a = array(
    5   => 35,
    16  => 22,
    7   => 22,
    3   => 22,
    11  => 22,
    9   => 27,
);

and I want to sort it by values ​​and remember its keys. The result I was expecting was:

$a = array(
    16  => 22,
    7   => 22,
    3   => 22,
    11  => 22,
    9   => 27,
    5   => 35,
);

So my first thought was asort:! Ok i did

asort($a);

But no - it did not just move 5 => 35to the end of the array. He changed my array to:

$a = array(
    11  => 22,
    3   => 22,
    7   => 22,
    16  => 22,
    9   => 27,
    5   => 35
);

You see? Keys with the same value are sorted in reverse order. Why?

+3
source share
4 answers

You cannot expect a specific sort order for equal values. From the PHP manual on sorting arrays :

If any of these sorting functions evaluates two members as equal, then the order is undefined (sorting is unstable).

+10

"" - .
, , ? .
, .

+2

, , , , . , /. , 4 22.

+1

Source: https://habr.com/ru/post/1763765/


All Articles