PHP strncasecmp | Compare First n Characters of String

The PHP strncasecmp is an inbuilt function in PHP. It compares first n characters of two strings. The function compares and tells us if one string is greater, smaller or equal to the other string. Also, this function is case-insensitive. Therefore, it treats lowercase and uppercase characters as the same. In this article, we will discuss the PHP strncasecmp Function.

Note: The function is similar to PHP strcasecmp Function with the difference that you can specify the number of characters to compare in this function.

Syntax

strncasecmp($string1, $string2, $numberOfCharacters)

Parameters

The PHP strncasecmp function expects three parameters. You need to pass both the strings you want to compare. Also, all the parameters are mandatory. The description of the parameters is as follows:

  • string1: The first string for comparison.
  • string2: The second string for comparison.
  • $numberOfCharacters: The third parameter defines the first n number of characters to compare in the strings.

Return Value

The function returns the following:

  • 0, if first n characters of both the strings are equal.
  • Returns a negative integer (< 0) , if first n characters of first string are smaller than in second string.
  • Returns a positive integer (> 0), if first n characters of first string are greater than in second string.

Example

For instance, consider the following example of using the PHP strncasecmp Function.

<?php 
  
// PHP program to illustrate the working of strcmp() 
$str1 = "Welcome to Concatly"; 
$str2 = "Welcome to String Functions"; 
$str3 = "WELCOME"; 
  
// In this case both the strings are equal. Search in case insensitive
print_r(strncasecmp($str1, $str3, 7));  
/* 0 */
  
// In this case the first is greater 
print_r(strncasecmp($str2, $str1, 14)); 
/* 16 */
  
// In this case the second is greater 
print_r(strncasecmp($str3, $str2, 10)) 
/* -3 */
  
?> 

You should observe the function returns 0 for the first 7 characters which are equal. It returns a positive integer when the first 14 characters of the first string are greater than the second string. Also, it returns a negative integer when the first 10 characters of the first string are smaller than the second string.

Conclusion

In conclusion, we discussed the PHP strncasecmp Function. You can read more about it on the Official PHP Documentation. Also, you can read about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

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