In this PHP tutorial, you shall learn how to compare given two strings using strcmp() function, with example programs.
PHP – Compare Strings
To compare strings in PHP, you can use strcmp() function. strcmp() can find if a string is smaller, equal to, or larger than the other string.
The syntax of strcmp() function to compare $string1 and $string2 is
</>
Copy
result = strcmp($string1, $string2)
strcmp() compares strings lexicographically.
- If $string1 precedes $string2 when arranged lexicographically in ascending order, $string1 is said to be smaller than $string2. In this case, strcmp($string1, $string2) returns negative value.
- If $string1 comes after $string2 when arranged lexicographically in ascending order, $string1 is said to be larger than $string2. In this case, strcmp($string1, $string2) returns positive value.
- If $string1 equals $string2, then strcmp($string1, $string2) returns 0.
Examples
1. Compare strings, given string1 is less than string2
In this example, we will take two strings: “apple”, “banana”. First string comes prior to second string when arranged in ascending order lexicographically. So, when we pass these two strings as arguments to strcmp(), it should return a negative value.
PHP Program
</>
Copy
<?php
$string_1 = "apple";
$string_2 = "banana";
$result = strcmp($string_1, $string_2);
echo $result;
?>
Output
