phpasort

How to sort values with special chars in array?


First, I set the proper locale to spanish:

setlocale(LC_ALL, 'es_ES');

This array holds a list of languages which must be reordered alphabetically.

$lang['ar'] = 'árabe';
$lang['fr'] = 'francés';
$lang['de'] = 'alemán';

So I do this:

asort($lang,SORT_LOCALE_STRING);

The final result is:

...and it should be:

The asort() function is sending the á character to the bottom of the ordered list. How can I avoid this issue? Thanks!

Solution linked by @Sbls

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');

Solution

  • Solution linked by @Sbls in comments

    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');