The PHP strncmp 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-sensitive. Therefore, it treats lowercase and uppercase characters as different. In this article, we will discuss the PHP strncmp Function.
Note: The function is similar to PHP strcmp Function with the difference that you can specify the number of characters to compare in this function.
strncmp($string1, $string2, $numberOfCharacters)
The PHP strncmp 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 strncmp 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 print_r(strncmp($str1, $str3, 7)); /* 0 */ // In this case the first is greater print_r(strncmp($str2, $str1, 14)); /* 16 */ // In this case the second is greater print_r(strncmp($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.