Skip to content

41: Replace strcoll() and SORT_LOCALE_STRING with Collator

Sort the same list of names under two locales. PHP 8.6 deprecates strcoll() and the SORT_LOCALE_STRING flag.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The intl extension.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable locale-collation.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/41-locale-collation/locale-collation.php
locale-collation.php
<?php
declare(strict_types=1);
foreach (['de_DE', 'sv_SE'] as $locale) {
$names = ['Zoe', 'Åsa', 'Anna'];
$collator = new Collator($locale);
if (!$collator->sort($names)) {
throw new RuntimeException($collator->getErrorMessage());
}
printf("%s %s\n", $locale, implode(', ', $names));
}
$swedish = new Collator('sv_SE');
$order = $swedish->compare('Zoe', 'Åsa');
if ($order === false) {
throw new RuntimeException($swedish->getErrorMessage());
}
echo 'Zoe comes first in Swedish: ', $order < 0 ? 'yes' : 'no', PHP_EOL;
de_DE Anna, Åsa, Zoe
sv_SE Anna, Zoe, Åsa
Zoe comes first in Swedish: yes

A Collator keeps the locale on an instance, so two parts of an application can sort differently. Use compare() for pairwise ordering, sort() for reindexed values, and asort() when you need to preserve keys.

Use asort() with labeled country codes as keys and inspect the sorted keys. They should still be associated with their original country names.

Continue with Drop the Third Argument to define().