1

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:

  • alemán
  • francés
  • árabe

...and it should be:

  • árabe
  • alemán
  • francés

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');
Community
  • 1
  • 1
Andres SK
  • 10,779
  • 25
  • 90
  • 152
  • wouldnt `ksort` work for you? I sorts the keys instead of the values. – Sbls Jan 04 '14 at 18:18
  • @Sbls That's won't work in my case. I have several language packs, the keys always stay the same, but the values won't. I always need to order by value. – Andres SK Jan 04 '14 at 18:19
  • possible dublicate of http://stackoverflow.com/questions/10649473/sort-an-array-with-special-characters-in-php Can you work with that question thread? – Sbls Jan 04 '14 at 18:20
  • One thing I see, is that you are setting the values of `$lang`, but sorting `$list['translate']`, is that the same array? – Alex Siri Jan 04 '14 at 18:22
  • AlexSiri: It wouldn't sort at all. Maybe a typo. @andufo: The whole thing works for me though. Well, árabe comes after alemán for me. But it doesn't come last. – Sbls Jan 04 '14 at 18:25
  • @AlexSiri yes, same array, ill correct that. – Andres SK Jan 04 '14 at 18:25

3 Answers3

1

Try using Collator::asort from the intl module:

<?php
$collator = collator_create('es_ES');
$collator->asort($array);
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
0

It is likely that the comparison checks the multibyte value of the character, and á in that case is probably greater than z, so it will show afterwards. If you want a comparison that does not take that into account, I see two possibilites:

  1. Sort using uasort and create your own comparison function.
  2. Generate a mapping from the ascii version of your strings, to the real one, and sort on the keys.
Alex Siri
  • 2,856
  • 1
  • 19
  • 24
0

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');
Andres SK
  • 10,779
  • 25
  • 90
  • 152