Skip to content

Novis\Intl\Collator::sort

Sorts a list of strings by the rules of a language and region.

Collator::sort returns the same strings in a new order. The order follows the locale you pass, such as "de" or "sv-SE". In German, ä sorts next to a. In Swedish, ä sorts after z. Equal strings keep the order they had in the list.

The options change how strings compare. strength sets which differences count: with Collator::Strength::Primary, case and accents do not count. caseFirst puts upper case or lower case first. numeric sorts digits by their value, so "9" comes before "10". ignorePunctuation skips spaces and punctuation.

Collator::sort throws a LogicError when the locale tag is not valid. A valid tag with no data of its own uses the general rules.

Good to know: the whole list is sorted in one call. To sort rows by a column, or to store the order in a database, use Collator::sortKeys.

Parameters

  • $stringsarray<string>
  • $localestring
  • $options?CollateOptionsdefault null

Return value

Returns array<string>.

Examples

Sort customer names

<?nvs
// Shows how to sort a list of names the way a German reader expects.
use Novis\Intl\Collator;
array<string> $names = ['Zimmermann', 'Ärzte', 'Bauer', 'Öztürk', 'Adler'];
// `Ä` sorts next to `A`, and `Ö` sorts next to `O`.
// This prints Adler, Ärzte, Bauer, Öztürk, Zimmermann.
echo Core\Str::join(Collator::sort($names, 'de'), ', '), "\n";
Output
Adler, Ärzte, Bauer, Öztürk, Zimmermann

The locale changes the order

<?nvs
// Shows that the same list sorts in a different order for each language.
use Novis\Intl\Collator;
array<string> $words = ['äpple', 'zebra', 'apple'];
// In German, `ä` sorts next to `a`. This prints apple äpple zebra.
echo Core\Str::join(Collator::sort($words, 'de'), ' '), "\n";
// In Swedish, `ä` is a letter after `z`. This prints apple zebra äpple.
echo Core\Str::join(Collator::sort($words, 'sv'), ' '), "\n";
Output
apple äpple zebra
apple zebra äpple

Numbers inside text

<?nvs
// Shows how to sort file names that contain numbers.
use Novis\Intl\Collator;
array<string> $files = ['page 10.txt', 'page 2.txt', 'page 1.txt'];
// Without options, digits sort one by one, so "10" comes before "2".
// This prints page 1.txt, page 10.txt, page 2.txt.
echo Core\Str::join(Collator::sort($files, 'en'), ', '), "\n";
// With `numeric: true`, digits sort by their value.
// This prints page 1.txt, page 2.txt, page 10.txt.
echo Core\Str::join(Collator::sort($files, 'en', { numeric: true }), ', '), "\n";
Output
page 1.txt, page 10.txt, page 2.txt
page 1.txt, page 2.txt, page 10.txt