strcmp() : Case sensitive string comparison

Compare strings case-sensitively

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
  • 0 : if both strings are equal or matching
  • < 0 : if string 1 is less than string 2
  • > 0 : if string 1 is greater than string 1

Case in sensitive string comparison use strcasecmp() function

Sample code using strcmp function to check two strings.

Example 1
$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

Example: Case-Insensitive String Comparison

$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).

Example: Comparing Strings with Different Encodings

$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().
String Functions strcasecmp(): Case-insensitive string comparison str_replace(): String replace


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer