strcmp() performs a binary-safe, case-sensitive comparison. Test whether the result is less than, equal to, or greater than 0 instead of depending on a particular non-zero magnitude.
$result = strcmp('apple', 'banana');if ($result < 0) {
echo 'apple sorts first';}var_dump(strcmp("Hello world", "HELLO WORLD") > 0); // true; case-sensitive comparison
Output is equal to
$str1 = "Hello World";$str2 = "hello world";$result = strcmp($str1, $str2);var_dump($result < 0); // true
if ($result === 0) {
echo "Both strings are matching";} else {
echo "Both strings are different";}
Output is
bool(true)
Both strings are different
Example 2
$str1="Hello World";$str2="Hello World";echo strcmp($str1,$str2); // Output is 0
echo "<br>";if(strcmp($str1,$str2)==0){echo "Both strings are matching";}else{echo "Both strings are different ";}
Output is here
0
Both strings are matching
$result = strcasecmp('Hello', 'hello');
if ($result === 0) {
echo 'The strings are equal (case-insensitive).';
} else {
echo 'The strings are not equal.';
}
Output
The strings are equal (case-insensitive).
$str1 = "Straße"; // Save this PHP file as UTF-8.
$str2 = "Strasse";if (strcmp($str1, $str2) === 0) {
echo "The strings are equal.";} else {
echo "The strings are not equal.";}
Output
The strings are not equal.
The final example compares two different UTF-8 strings. strcmp() compares their bytes; it does not transliterate text or perform locale-aware collation. For locale-aware comparison, see strcoll().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.