PHP strcmp() Function: String Comparison Guide
The strcmp function in PHP is used to compare two strings. It compares the two strings based on dictionary order (ASCII values) and returns an integer value to indicate the comparison result. Essentially, the strcmp function works as follows:
- Return 0 if two strings are equal.
- If the first string is less than the second string (in dictionary order), return a negative number.
- Return a positive number if the first string is greater than the second string in dictionary order.
Here is a simple example:
$str1 = "apple";
$str2 = "banana";
$result = strcmp($str1, $str2);
if ($result == 0) {
echo "The two strings are equal.";
} elseif ($result < 0) {
echo "$str1 comes before $str2.";
} else {
echo "$str1 comes after $str2.";
}
In the example above, the strcmp function compared the strings “apple” and “banana” and outputted different messages based on the comparison result.