PHP string strcmp() FunctionString comparison is one of the most common tasks in programming and development. strcmp() is a string comparison function in PHP. It is a built-in function of PHP, which is case sensitive, means it treats capital and the small case separately. It is used to compare two strings from each other. This function compares two strings and tells whether a string is greater, less, or equal to another string. strcmp() function is binary safe string comparison. Note: strcmp() function is case sensitive as well as binary safe string comparison.Syntax:Parametersstrcmp() function accepts two strings parameter, which is mandatory to pass in the function body. Both parameters are mandatory to pass in strcmp() function(). Description of the following parameters is given below.
Value return by strcmp()This function returns integer value randomly based on the comparison. Return 0 - It returns 0 if both strings are equal, i.e., $str1 = $str2 Return < 0 - It returns negative value if string1 is less than string2, i.e., $str1 < $str2 Return >0 - It returns positive value if string1 is greater than string 2, i.e., $str1 > $str2 Note: It calculates ASCII value of the string and then compares both strings to check that they are equal, greater or less from each other.Difference between strcoll() and strcmp() functionsstrcoll() and strcmp() both are string comparison function of PHP, but they slightly differ with each other. Strcoll() takes the bytes and transform them using locale, then compares the result, whereas, strcmp() takes the bytes of string one by one and then compares them whatever the bytes are. Example 1Output: 0 because both strings are equal. 6 because the first string is greater than the second string. Remark: Second string comparison has returned the value 6 because the first string is greater than the second string by 6 characters, including whitespace. Example 2Output: -1 because the first string is less than the second string. 1 because the first string is greater than the second string. Example 3Output: 1 because the first string is greater than the second string. -6 because the first string is less than the second string. Remark: Second string comparison has returned -6 because the first string is 6 characters smaller than the second string, including whitespace.
Next TopicPHP String Functions |