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.
Below some examples are given from which you can learn the practical implementation of this function in the program.
Input: $string1 = "Hello World", $string2 = "HELLO ", $len = 5; //case-insensitive Output: 0 Input: $string1 = "Hello World ", $string2 = "Hello ", $len = 11; Output: 6 Input: $string1 = "Hello PHP! ", $string2 = "PHP", $len = 9 Output: -8 Input: $string1 = "PHP! ", $string2 = "Hello PHP", $len = 9 Output: 8 Input: $string1 = "Hello ", $string2 = "Hello PHP", $len = 9 Output: -4
Following some detailed examples are given below -
It is the simple example of strncasecmp() which shows that it is case-insensitive function.
In this example, the function has returned 13, because string1 is greater than string2.
In this example, the function has returned -13, because string1 is smaller than string2.
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).
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.
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.