phpsortinglocalizationsetlocaleasort

How to sort accented letters as they are unaccented in php?


I am working on a php code as shown below which on echo returns the array below it.

ksort( $alpha_programs );  // Line A
echo '<pre>'; print_r($alpha_programs); echo '</pre>'; // Line B

Line B display the following array:

Array
(
    [Des Canadiens exceptionnels] 
    [Did You Know?] 
    [Documentaires] 
    [Dossier public] 
    [Débats Vote 2015] 
    [Délibérations de la Chambre des communes] 
    [Délibérations du Sénat] 
)

Problem Statement:

I am wondering what changes I should make in the php code above at Line A so that accented letters should sort as though they are unaccented as shown below:

   Array
    (

       [Débats Vote 2015]
       [Délibérations de la Chambre des communes]
       [Délibérations du Sénat]
       [Des Canadiens exceptionnels]
       [Did You Know?]
       [Documentaires]
       [Dossier public]
    }

This is what I have tried but it doesn't seem to sort/work properly.

setlocale(LC_COLLATE, 'fr_CA.utf8');
asort($alpha_programs, SORT_LOCALE_STRING);

Solution

  • The setlocale function requires the corresponding locale to be available in your system. This varies depending on your platform, but on linux systems you can check available locales by running locale -a.

    You can check if the function call is failing by checking the return value, since it can return false.

    If that's the case, you can use a Collator from the intl extension instead:

    $collator = Collator::create('fr_CA.utf8');
    $collator->sort($alpha_programs);
    

    Demo

    Updated Demo with associative array