1

When I was testing a bit for fun I found this weird irregularity in the PHP asort() function. When executing the following code:

$array = array(
    "Player 1" => 5,
    "Player 2" => 4,
    "Player 3" => 4,
    "Player 4" => 4,
    "Player 5" => 4
);
asort($array);
print_r($array);

I would expect to see "Player 1" be moved to the bottom, and nothing more. However, the "Player 2" and "Player 3" also switch resulting in:

Array
(
    [Player 3] => 4  // <- Swapped
    [Player 2] => 4  // <- Swapped
    [Player 4] => 4
    [Player 5] => 4
    [Player 1] => 5
)

When I, however, do the reverse of:

$array = array(
    "Player 1" => 4,
    "Player 2" => 4,
    "Player 3" => 4,
    "Player 4" => 4,
    "Player 5" => 3
);
asort($array);
print_r($array);

I get the expected result where only "Player 5" gets put at the start resulting in:

Array
(
    [Player 5] => 3
    [Player 1] => 4
    [Player 2] => 4  // <- Not swapped
    [Player 3] => 4  // <- Not swapped
    [Player 4] => 4
)

My question here is how does this function deal with these duplicates and why do 2 and 3 swap in the first example, but not in the second?

J0R1AN
  • 583
  • 7
  • 10
  • From the manual page you linked: "If two members compare as equal, their relative order in the sorted array is undefined." – Nick Aug 06 '20 at 12:09
  • It's a legit question. However in how many cases is this bad? If you directly access it with key you would say $array['player_2']. If you want to work with indexes, the result will still be the same.. – Wimanicesir Aug 06 '20 at 12:18
  • I agree it wouldn't be that big of a problem, I was just curious how PHP defines it since with my tests it looked quite inconsistent – J0R1AN Aug 06 '20 at 12:20
  • Well as Nick said, "If two members compare as equal, their relative order in the sorted array is undefined.". This has been done on purpose. If you test this with PHP 5.6 or lower, you would get the result you expect. It would be slightly slower though. – Wimanicesir Aug 06 '20 at 12:23

0 Answers0