I have an array that holds the names of languages in spanish:
$lang[\"ko\"] = \"coreano\"; //korean
$lang[\"ar\"] = \"árabe\"; //arabic
$lang[\"es\"] = \"esp
The documentation for setlocale mentions that
Different systems have different naming schemes for locales.
It's possible that your system does not recognize the locale as es_ES
. If you are on Windows, try esp_ESP
instead.
Try sorting by translitterated names:
function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');
print_r($lang);
Try this
setlocale(LC_COLLATE, 'nl_BE.utf8');
$array = array('coreano','árabe','español','francés');
usort($array, 'strcoll');
print_r($array);
This is a non problem!
Your initial solution works exactly as expected,
Your problem is the setlocale function that is failing to set the locale and by consequence the asort($array, SORT_LOCALE_STRING)
fails to sort as you expect it
You can try your own code at phptester.net that does accept setlocale():
$lang["ko"] = "coreano"; //korean
$lang["ar"] = "árabe"; //arabic
$lang["es"] = "español"; //spanish
$lang["fr"] = "francés"; //french
asort($lang,SORT_LOCALE_STRING);
echo "<pre>";
print_r($lang);
echo "</pre>";
echo "<pre>";
/*this should return es_ES;
if returns false it has failed and asort wont return expected order
*/
var_dump(setlocale(LC_ALL,'es_ES'));
echo "</pre>";
asort($lang,SORT_LOCALE_STRING);
echo "<pre>";
print_r($lang);
You defined your locale incorrectly in setlocale()
.
Change:
setlocale(LC_ALL,'es_ES.UTF-8');
To:
setlocale(LC_ALL,'es_ES');
Output:
Array ( [ar] => árabe [ko] => coreano [es] => español [fr] => francés )