使用arsort排序不稳定[重复]

This question already has an answer here:

There is strange issue in php asort, arsort.

I am taking example of arsort

Case1

$a = array(
    1 => 2,
    2 => 1,
    3 => 2,
    4 => 1
);
arsort($a);
var_dump($a);

Output:

array(4) {
  [3] =>
  int(2)
  [1] =>
  int(2)
  [4] =>
  int(1)
  [2] =>
  int(1)
}

Here at index (3,1) and (4,2) are sorted in descending order because at index 3 and 1 values are same. Same for index 4 and 2.

Case2

$a = array(
    1 => 2,
    2 => 1,
    3 => 2
);
arsort($a);
var_dump($a);

Output:

array(3) {
  [1] =>
  int(2)
  [3] =>
  int(2)
  [2] =>
  int(1)
}

Here at index (3,1) are sorted in ascending order and still at index 3 and 1 values are same.

Is there any solution for this issue? As I want that ordering should be certain. Like sort in either descending or ascending order if value at some indices are same.

</div>

According to the PHP documentation:

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

You can't know exactly which behaviour is correct, with testing just with 2 elements. Here's an array with multiple elements (odd and even).

even number:

<?php

$a = array(
    1 => 2,
    2 => 1,
    3 => 2,
    4 => 1,
    5 => 2,
    6 => 1,
    7 => 2,
    8 => 1,
    9 => 2,
    10 => 1,
    11 => 2,
    12 => 1
);
arsort($a);
var_dump($a);

Result:

array (size=12)
  1 => int 2
  7 => int 2
  5 => int 2
  11 => int 2
  9 => int 2
  3 => int 2
  10 => int 1
  12 => int 1
  6 => int 1
  2 => int 1
  4 => int 1
  8 => int 1

odd number

<?php

$a = array(
    1 => 2,
    2 => 1,
    3 => 2,
    4 => 1,
    5 => 2,
    6 => 1,
    7 => 2,
    8 => 1,
    9 => 2,
    10 => 1,
    11 => 2,
    12 => 1,
    13 => 2
);
arsort($a);
var_dump($a);

Result

array (size=13)
  9 => int 2
  11 => int 2
  13 => int 2
  1 => int 2
  7 => int 2
  3 => int 2
  5 => int 2
  12 => int 1
  2 => int 1
  4 => int 1
  8 => int 1
  6 => int 1
  10 => int 1

The question is now, where did it add the 13th element (=2)? it's added just after the 11th element and before the first element...this means that there's no rule here. (At least according to what we see).

We can't say that it follows any rule with testing with just 2 variables like what you did, because you saw (1,3) and you presumed that it's sorted by key. Which is apparently not the case with multiple variables.