Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to compare two strings in PHP?

Answer: Using strcmp() function

We can compare the two strings in PHP using the predefined strcmp() function. This function is case sensitive which means it treats the upper case and lowercase of the same letter as two different letters.

For a case-insensitive comparison, we have to use the strcasecmp() function.

Example: Using strcmp() function

In this example, we have used the strcmp() function to compare the two strings in PHP.

<!DOCTYPE html>
<html>
<head>
  <title>Compare two string</title>
</head>
<body>
	<?php
		$str1 = "Hello World!";
		$str2 = "Hello world!";
		if(strcmp($str1, $str2) == 0){
			echo "Strings are same";
		}else{
			echo "Strings are not same";
		}
	?>
</body>
</html>

Output


Strings are not same

Using (==) operator

We can also compare the two strings using the equality operator. This operator requires two values to perform the comparison between them. It returns true when both the values are equal and returns false when both the values are not equal.

This operator compares the value of the variable, not their data types.

Example: Using equality (==) operator

In the given example, we have used the equality (==) operator to compare two strings and check whether they are equal or not.

<!DOCTYPE html>
<html>
<head>
  <title>Compare two string</title>
</head>
<body>
	<?php
		$str1 = "Hello World!";
		$str2 = "Hello World!";
		if($str1 == $str2){
			echo "Strings are same";
		}else{
			echo "Strings are not same";
		}
	?>
</body>
</html>

Output


Strings are same

Conclusion

In the lesson, we have learned how to compare two strings. So here, we have used two methods to compare two strings. Firstly, we have used the predefined PHP function that is strcmp(). This function compares two strings, and it performs the case-sensitive comparison. Then we have used the equality (==) operator to compare two strings. It returns true when the strings are equal and returns false when the strings are not equal.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.