Search code examples
phpsortingphp-5.3

Utf8 Sort Array


i have some problems with sorting an array.

List

0 => string 'Australien' (length=10)
1 => string 'Belgien' (length=7)
2 => string 'Botswana' (length=8)
3 => string 'Brasilien' (length=9)
4 => string 'Bulgarien' (length=9)
5 => string 'Burma' (length=5)
6 => string 'China' (length=5)
7 => string 'Costa Rica' (length=10)
73 => string 'Ägypten' (length=8)

But Ägypten should be after Australien. I already tried with the Collator class but our client wont install the extension.


Solution

  • You can use setlocale along with first parameter LC_COLLATE and second locale with en_US.utf8 and simply sort using usort along with strcoll try as

    setlocale(LC_COLLATE, 'en_US.utf8');
    $array = array('Australien','Belgien','Botswana','Brasilien','Bulgarien','Burma','China','Costa Rica','Ägypten');
    usort($array, 'strcoll'); 
    print_r($array);
    

    Demo