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.
strncasecmp($string1, $string2, $numberOfCharacters)
The PHP strncasecmp function expects three parameters. You need to pass both the strings you want to compare. Also, all
- 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.
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.
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.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.