Reputation: 28767
Note! This question is outdated (thanks mickmackusa).
Edit: This question seems to be a duplicate of Preserve key order (stable sort) when sorting with PHP's uasort
Someone has been using arsort()
to sort an array parsed from HTTP_ACCEPT_LANGUAGE
under the assumption that it is a stable sort. But it's not: https://bugs.php.net/bug.php?id=53553. Now I have a bug and I am a bit at a loss how to fix the bug without resorting to hacks.
I have this header from a mobile client:
HTTP_ACCEPT_LANGUAGE: de-CH, en-US
and this gets parsed to:
Array (
[de-CH] => 1
[en-US] => 1
)
After parsing arsort($array, SORT_NUMERIC)
is used to sort the languages corresponding to their q values. But because German and English has the same q value, arsort()
swaps German and English. How can I sort the array so that the insertion order is preserved?
Upvotes: 1
Views: 806
Reputation: 514
Crazy enough PHP :)
It is already mentioned in the documentation
http://php.net/manual/en/function.arsort.php
If two members compare as equal, their relative order in the sorted array is undefined.
And funny enough, it works differently in PHP 7
Upvotes: 0
Reputation: 32155
You don't need to sort the array if you're only looking for the preferred language:
<?php
function findPrefferedLanguage($languages) {
foreach ($languages as $lang => $weight) {
if (empty($key) || ($weight > $languages[$key])) {
$key = $lang;
}
}
return $key;
}
$foo = array('es' => .6, 'en' => 1, 'fr' => 1, 'de' => .5);
var_dump(findPrefferedLanguage($foo)); // en
Hastily tested... there's probably some edge-cases that will generate errors/warnings.
Upvotes: 1
Reputation: 28929
Your problem isn't the unstable nature of the sort functions, but rather that you have two elements which have the same value, but you're expecting one to be sorted before the other.
If de-CH
should be weighted higher than en-US
, indicating that the client prefers German over English, then don't give them both values of 1
.
Upvotes: 0