How to compare two strings in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP strcmp() function

You can use the PHP strcmp() function to compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2; returns > 0 if str1 is greater than str2, and 0 if they are equal.

  • <?php
  • $str1 = "Hello";
  • $str2 = "Hello World";
  • echo strcmp($str1, $str2); // Outputs: -6
  • ?>

The PHP strcmp() function compare two strings in a case-sensitive manner. If you want case-insensitive comparison, you can use the strcasecmp() function.

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.