Javatpoint Logo
Javatpoint Logo

strncasecmp() function in PHP

The strncasecmp() is a case-insensitive, built-in function of PHP. It compares two strings for the first n characters. This function is similar to the strcasecmp() function with a difference. In strncasecmp(), we can specify the number of characters from both the strings for comparison, whereas, strcasecmp() does not have the length parameter. The strncasecmp() is a binary-safe function.

Note: The strncasecmp() is a case-insensitive and binary-safe function.


The strncasecmp() function has the following syntax:

All the three parameters are mandatory to pass in this function. It returns an integer value after comparison.


$string1 (required): It is the first string which is used in the comparison. It's a mandatory parameter.

$string2 (required): It is the second mandatory string which is used in the comparison.

$length: It is the last and mandatory parameter of this function which specifies the length of the string to be used in the comparison.

Return Values

Return Values Description
Return < 0 If the string1 is less than string2, i.e., $string < $string2.
Return 0 If both strings are equal.
Return > 0 If the string1 is greater than string2, i.e., $string > $string2.


Below some examples are given from which you can learn the practical implementation of this function in the program.

$string1 = "Hello World", $string2 = "HELLO ", $len = 5;	//case-insensitive
Output: 0

$string1 = "Hello World ", $string2 = "Hello ", $len = 11;	
Output: 6

$string1 = "Hello PHP! ", $string2 = "PHP", $len = 9
Output: -8

$string1 = "PHP! ", $string2 = "Hello PHP", $len = 9
Output: 8

$string1 = "Hello ", $string2 = "Hello PHP", $len = 9
Output: -4

Following some detailed examples are given below -

Example 1

It is the simple example of strncasecmp() which shows that it is case-insensitive function.



Example 2


In this example, the function has returned 13, because string1 is greater than string2.


Example 3


In this example, the function has returned -13, because string1 is smaller than string2.


Example 4



Example 5


In the above example, this function has returned 18 because string2 is greater than string1. ASCII value of e (101) is greater than W (87).


Example 6


In this example, the function has returned -4 because string1 is smaller than string2. In string2, there is r in place of n at the end of the afternoon. ASCII value of r (114) is greater than n (110), which is less.


Example 7

If we do not provide the length in the function for comparison, then it would show an error.


We can see in the output that it generate a warning which is, the function expects three parameters where only two parameters are given in the program.

PHP String strncasecmp() function

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA