tags:

views:

88

answers:

4

Hello !

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 ?

+2  A: 

"Why" is another question.
But it actually did what you were asking for, didn't it?
Key order weren't determined.
If you want certain order of keys, you should state it in the exercise conditions

Col. Shrapnel
The point is I need to keep keys order too.
hsz
@hsz you may need to build a manual function for that to re-sort the keys of equal values after the first sorting. I can't see a ready-made function for that - or a user-defined function that would be suitable for this - in [the list](http://www.php.net/manual/en/array.sorting.php) (but I can be wrong)
Pekka
+9  A: 

You can't expect a certain sorting order for equal values. From the PHP manual on Sorting Arrays:

If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

Pekka
+1  A: 

Depending on the sort algorithm, it probably started sorting in another manner than just detecting that it should only move that single pair. But it ended up with a validly sorted array maintaining keys/values. they only look swapped cuz you have 4 keys with values of 22.

aularon
+2  A: 

http://en.wikipedia.org/wiki/Sorting_algorithm#Stability

in short, making sure that the order of the already sorted keys remains the same would cost computation time (and whoever designed the function at PHP decided it wasn't worth it)

zaphod