It’s simple enough to check if strings are exactly equal in PHP, just use ==, the standard comparison operator. However, this assumes we are only using strings or string type variables. It is a case sensitive comparison only. In this short article we are going to go though some alternate string comparison options and learn what they are good for.

First is exact type comparison, ===

$str1 = "100DollarsCash";
if($str1 == 100) {
	echo "it equals 100. ";
}
if($str1 === 100) {
	echo "it is 100. ";
}


There are 2 if statements above, the first was true and would echo the text. That is because $str1 was forced into being a number. The second if statement was false and did not print, because the === operator tests if they are the same type as well as if they are equal. In a string comparison it also would not be considered equal since “100” is not the same as “100DollarsCash”

$string_compare_result = strcmp("100", "100DollarsCash");
echo $string_compare_result;

As we said the 2 strings are not equal. In the above code strcmp is a function that takes 2 strings, does a case sensitive string comparison, and returns whether they are equal. The return value is not what one might expect. When I ran this it echoes -11. The function returns 0 if the strings are equal. Otherwise it returns a number representing one string being greater or lesser. The number usually doesn’t matter, it’s recommended to use the function like this:

$string_compare_result = strcmp("100", "100");
if($string_compare_result == 0) {
	echo "they are equal";
} else {
	echo "they are not equal";
}

It takes some getting used to since we think of 0 as meaning false, but with string comparison functions it means they are equal.

$string_compare_result = strcmp(100, "100");
if($string_compare_result == 0) {
	echo "they are equal";
}

Notice the change this time, it asks is 100 equal to “100”. If the Statement used 100 === “100” they would not be considered the same. With strcmp they are considered equal though.

$str1 = "100DollarsCash";
$string_compare_result = strcasecmp($str1, "100dollarscash");
echo $string_compare_result;

In this example we compared “100DollarsCash” and “100dollarscash” with a different function called strcasecmp(). The function is the same as strcmp() but it considers capitals and lowercase equal. The 2 strings are equal.

I have just one final tip which is often used. When comparing something from a file or user input there may be cases where invisible / whitespace characters are causing things to be unequal when it isn’t desired. The trim function can eliminate those characters from the front and back of a string to make things simpler.