Search code examples
phpasort

PHP's asort does not work properly?


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. Result that I expected 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 didn't just move 5 => 35 to the end of the array. It 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 reverse sorted. Why ?


Solution

  • It depends on whether a sorting algorithm is stable or not. For a stable sort, upgrade your PHP version. PHP manual on Sorting Arrays:

    If any of these sort functions evaluates two members as equal then they retain their original order. Prior to PHP 8.0.0, their order were undefined (the sorting was not stable).