PHP string compare

Home - Tutorials - Basics

In this article I will show you how you can use PHP string compare functions.

Tutorial info:

Name:PHP string compare
Total steps:1

Bookmark PHP string compare

Bookmark and Share

Step 1 - PHP string compare solutions

PHP string compare

Time to time you want to compare various strings and control your script execution regarding the result. You can do this in more ways. The most simple way to use the compare operator (==) as follows:

  1. <?php
  2. $str1 = "Test";
  3. $str2 = "Test";
  5. if ($str1 == "Test") echo "OK-1";
  6. if ($str1 == $str2) echo "OK-2";
  7. ?>

However you can use PHP built in functions as well like strcmp and strcasecmp. These functions make a binary safe string comparison where the strcasecmp is a case-insensitive version. With this functions you can also decide which string is greater or smaller as it returns < 0 if STR1 is less than STR2 > 0 if STR1 is greater than STR2, and 0 if they are equal. So you can use these functions like this:

  1. <?php
  2. $str1 = "Test";
  3. $str2 = "Test";
  4. $str3 = "Apple";
  5. $str4 = "Zebra";
  7. if (strcmp($str1,$str2) == 0) echo "OK";
  8. if (strcmp($str1,"Test") == 0) echo "OK";
  9. if (strcmp($str1,$str3) > 0) echo "$str1 > $str3";
  10. if (strcmp($str1,$str4) < 0) echo "$str1 < $str4";
  11. ?>

Sometimes it can happen that the strings seems to be equal but the comparison reports that they are different. The most common problem in this case that there are some spaces before or after the relevant text. This results that the strings are different. To solve this problem it make sense to use the PHP built in trim function to remove all unwanted spaces like this:

  1. <?php
  2. $str1 = "Test";
  3. $str2 = " Test ";
  5. if ($str1 == $str2) echo "OK-1";
  6. if ($str1 == trim($str2)) echo "OK-2";
  7. if (strcmp($str1,$str2) == 0) echo "OK-3";
  8. if (strcmp($str1,trim($str2)) == 0) echo "OK-4";
  9. ?>

The built in trim function definitely works best when supported by PHP hosting.

Tags: php string compare, string compare, php string, string, compare

PHP string compare - Table of contents
Step 1 - PHP string compare solutions

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.0106