41: Replace strcoll() and SORT_LOCALE_STRING with Collator
Overview
Section titled “Overview”Sort the same list of names under two locales. PHP 8.6 deprecates strcoll() and the SORT_LOCALE_STRING flag.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
intlextension. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable locale-collation.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/41-locale-collation/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;Expected Result
Section titled “Expected Result”de_DE Anna, Åsa, Zoesv_SE Anna, Zoe, ÅsaZoe comes first in Swedish: yesWhy It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Use asort() with labeled country codes as keys and inspect the sorted keys. They should still be associated with their original country names.
Wrap-up
Section titled “Wrap-up”Continue with Drop the Third Argument to define().