collator_compare
collator_compare($collator, $a, $b)
Compares two texts by the rules of a language: returns −1 when $a comes before $b, 1 when it comes after it, and 0 when they are equal by the rules. Useful as a comparison function for usort().
Parameters
- $collator – a Collator object.
- $a, $b – the texts to compare.
Examples
$c = collator_create("en_US");
echo collator_compare($c, "café", "cafe"); // 1
echo collator_compare($c, "apple", "Banana"); // -1
// database rows by name
$products = array(array("name" => "Zucchini"), array("name" => "éclair"), array("name" => "Apple"));
usort($products, function ($a, $b) use ($c) {
return collator_compare($c, $a["name"], $b["name"]);
});
echo implode(", ", array_column($products, "name")); // Apple, éclair, Zucchini
Things to watch out for
- The result does not have to be exactly −1 and 1 – compare by the sign (
< 0,> 0). - Equality by the rules of a language (0) does not mean identical strings – with the strength
Collator::PRIMARY“e” and “é” are equal.
Related functions:
collator_create()
collator_sort()
usort()
strcmp()
strcoll()