The PHP strcoll() function is used to compare two strings based on the current locale settings. It performs a locale-aware comparison, which makes it more suitable for handling strings in different languages and regional settings compared to binary comparison functions like strcmp().
Syntax
int strcoll ( string $string1 , string $string2 )
$string1: The first string to be compared. $string2: The second string to be compared. Return Value: This function returns:
Less than 0 if $string1 is less than $string2.
Greater than 0 if $string1 is greater than $string2.
0 if $string1 is equal to $string2.
Basic Example of strcoll()
In the following example, we compare two strings using the strcoll() function.
$str1 = "apple";
$str2 = "banana";
echo strcoll($str1, $str2); // Output will be less than 0 because "apple" is less than "banana"
Output:
-1
Example with Equal Strings
Here, we compare two identical strings, and the function returns 0.
$str1 = "apple";
$str2 = "apple";
echo strcoll($str1, $str2); // Output will be 0 because both strings are the same
Output:
0
Locale-Aware Example
To see how strcoll() behaves differently in various locales, let's set the locale to a specific language.
setlocale(LC_COLLATE, 'en_US'); // Set locale to US English
$str1 = "apple";
$str2 = "Apple";
echo strcoll($str1, $str2); // Output will be greater than 0 because "apple" > "Apple" in US locale
setlocale(LC_COLLATE, 'fr_FR'); // Set locale to French
echo strcoll($str1, $str2); // Output might change depending on French locale rules
Output:
1
1
Comparing Numeric Strings
When comparing numeric strings, strcoll() treats them like strings based on the current locale, not as numbers.
$str1 = "123";
$str2 = "456";
echo strcoll($str1, $str2); // Output will be less than 0 because "123" is less than "456"
Output:
-1
Case-Sensitive Comparison
Unlike strcasecmp(), the strcoll() function performs a case-sensitive comparison based on locale settings.
$str1 = "Hello";
$str2 = "hello";
echo strcoll($str1, $str2); // Output depends on the locale, but typically it's case-sensitive
Output:
-1
Conclusion
The PHP strcoll() function is useful when you need locale-aware string comparison. It’s more appropriate than binary comparison functions when dealing with strings in different languages or regional formats. By using the locale settings, it ensures that comparisons are done according to cultural and linguistic rules, making it highly flexible for international applications.
← String FunctionsNext: strrev() - Reversing a String →chunk_split(): Split a string into smaller chunks →
Passionate about coding and teaching, I publish practical tutorials on PHP, Python,
JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and
project‑oriented with real examples and source code.