How to Use strcoll() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

In PHP, the `strcoll()` function is used for string comparison based on the current locale. It compares two strings and returns 0 if they are equal, a negative value if the first string is less than the second one, and a positive value if the first string is greater than the second one, based on the locale-specific collation order.

Starting from PHP 8.1, `strcoll()` accepts arguments of type `string` or `Stringable`, and it performs a binary safe comparison by default. This means it compares strings byte by byte without interpreting them as characters in any encoding.

Here’s an example demonstrating the usage of `strcoll()` function:

<?php

// Example strings for comparison
$str1 = "apple";
$str2 = "banana";

// Performing string comparison using strcoll()
$result = strcoll($str1, $str2);

// Outputting the result
if ($result === 0) {
echo "$str1 is equal to $str2\n";
} elseif ($result < 0) {
echo "$str1 is less than $str2\n";
} else {
echo "$str1 is greater than $str2\n";
}

?>

This script will output `”apple is less than banana”`, as “apple” comes before “banana” alphabetically.

In PHP 8.1 and later versions, you can also specify a locale for the comparison by passing it as the third argument to `strcoll()`. If you want to perform a binary-safe comparison, you can pass `null` as the locale argument.

<?php

// Example strings for comparison
$str1 = "apple";
$str2 = "banana";

// Performing string comparison using strcoll() with locale set to null
$result = strcoll($str1, $str2, null);

// Outputting the result
if ($result === 0) {
echo "$str1 is equal to $str2\n";
} elseif ($result < 0) {
echo "$str1 is less than $str2\n";
} else {
echo "$str1 is greater than $str2\n";
}
?>

This will produce the same result as the previous example.