1

I'm trying to sort an array of French words alphabetically. Here's what I did:

$locale = setlocale(LC_ALL, 'fr_FR.UTF-8');

print_r($locale);
echo PHP_EOL;

$verbs = [
    'être',
    'faire',
    'ecouter',
    'dire',
    'euphoriser',
];

sort($verbs, SORT_LOCALE_STRING);

print_r($verbs);

On my web server, it works as expected, printing:

fr_FR.UTF-8
Array
(
    [0] => dire
    [1] => ecouter
    [2] => être
    [3] => euphoriser
    [4] => faire
)

The accent is ignored and ê behaves like e. But there's a problem with PHP in my console on macOS. The same app prints the following result:

fr_FR.UTF-8
Array
(
    [0] => dire
    [1] => ecouter
    [2] => euphoriser
    [3] => faire
    [4] => être
)

The locale is found, because setlocale() returns fr_FR.UTF-8 correctly (it returns false for invalid locale). But for some reason, être is the last element of the array after sorting. It's like this French locale is broken, or never used. How can I make my console PHP use locale correctly?

When I run locale -a, fr_FR.UTF-8 is listed as one of available locales on my machine.

I'm using PHP 7.4.9.

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
  • 1
    Not sure what the issue could be here, but you could try using the [`Collator`](https://www.php.net/Collator) class in case it's better. – Jeto Aug 31 '20 at 14:54
  • @Jeto the Collator, surprisingly, worked! It's weird, because even if I skip `setlocale()` and pass whatever to Collator's constructor, it still sorts correctly. I tried with `$collator = new Collator('x');` and it still works. Weird weirdness. – Robo Robok Aug 31 '20 at 15:06
  • Yeah `Collator` is supposed to work with its injected locale, as opposed to the "global" one. Anyway, glad that worked. – Jeto Aug 31 '20 at 15:16
  • Does setting `LC_COLLATE` instead of `LC_ALL` change anything? (It really shouldn't but...) – Álvaro González Aug 31 '20 at 15:31
  • @ÁlvaroGonzález no, it doesn't change the behavior. – Robo Robok Aug 31 '20 at 16:40
  • @Jeto do you know how to do `ksort()` with the `Collator`? It doesn't seem to allow that. – Robo Robok Aug 31 '20 at 16:41
  • @RoboRobok Guess you could do [something like this](https://3v4l.org/gELn7) then (you can also use your already instanced `Collator` instance if you already have one). – Jeto Aug 31 '20 at 17:50

0 Answers0