Sorting and Comparing in PHP

PHP’s built-in text sorting and comparison functions also operate on a byte-by-byte basis following the order of letters in the English alphabet. Turn to the Collator class to do these operations in a character-aware manner.

First, construct a Collator object, passing its constructor a locale string. This string references a particular country and language and tells the Collator what rules to use. There are lots of finicky details about what can go into a locale string, but usually it’s a two-letter language code, then _, then a two-letter country code. For example, en_US for US English, or fr_BE for Belgian French, or ko_KR for South Korean. Both a lan­guage code and a country code are provided to allow for the different ways a language may be used in different countries.

The sort() method does the same thing as the built-in sort() function, but in a language-aware way: it sorts array values in place. Example 20-4 shows how this func­tion works.

Example 20-4. Sorting arrays

// US English

$en = new Collator(‘en_US’);

// Danish

$da = new Collator(‘da_DK’);

$words = array(‘absent’,‘åben’,‘zero’);

print “Before sorting: ” . implode(‘, ‘, $words) . \n;

$en->sort($words);

print “en_US sorting: ” . implode(‘, ‘, $words) . \n;

$da->sort($words);

print “da_DK sorting: ” . implode(‘, ‘, $words) . \n;

In Example 20-4, the US English rules put the Danish word aben before the English word absent, but in Danish, the a character sorts at the end of the alphabet, so aben goes at the end of the array.

The Collator class has an asort() method too that parallels the built-in asort() method. Also, the compare() method works like strcmp(). It returns -1 if the first string sorts before the second, 0 if they are equal, and 1 if the first string sorts after the second.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *