PHP strcmp is an inbuilt Function in PHP. It compares two strings in a case-sensitive manner. Therefore, it treats lowercase and uppercase strings differently. The function compares and tells us if one string is greater, smaller or equal to the other string. In this article, we will discuss the PHP strcmp Function. Also, we will discuss a few examples of using it.
The function expects two parameters. You need to pass both the strings you want to compare. Also, both
- string1: The first string for comparison.
- string2: The second string for comparison.
The function returns the following:
- 0, if string1 = string2.
- Returns a negative integer (< 0) , if string1 < string2.
- Returns a positive integer (> 0), if string1 > string2.
Consider the following example:
<?php // PHP program to illustrate the working of strcmp function $string1 = "Welcome to Concatly"; $string2 = "Bringing Knowledge Together"; $string3 = "Welcome to Concatly"; // In this case both the strings are equal print_r(strcmp($string1, $string3)); /* 0 */ // In this case the first is greater print_r(strcmp($string2, $string1)); /* -21 */ // In this case the second is greater print_r(strcmp($string3, $string2)) /* 21 */ ?>
You should observe in the above example, the function returns 0 when both the strings are same. It returns a negative value when string1 is smaller than string2. Also, it returns a positive value when string1 is greater than string2.
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.