How to Compare Two Strings in PHP?

How to Compare Two Strings in PHP?

  • PHP
  • 3 mins read

In this tutorial, you will learn to compare two strings in PHP. There is a predefined function(i.e., strcmp()), which is used to compare between two strings and it is case-sensitive.

Here is The Syntax of strcmp() function:

strcmp(str1,str2), here strcmp() is containing two strings as parameters(i.e str1 and str2).strcmp(str1,str2)will return 0, if both strings are equal.

Here is a standard program for using strcmp() function for two strings "happy" and "happy".

<html>
<body>
<?php
$a="happy";
$b="happy";
$c=strcmp($a,$b);//here both strings are equal
echo $c;

?>
</body>
</html>

Output:0

Now We will give an example where two strings are not equal, but the alphabetical position of the first letter of one string("amit") is smaller than the alphabetical position of the first letter of the second string("babu"):

<html>
<body>
<?php
$a="amit";
$b="babu";
$c=strcmp($a,$b);//here first string("amit")<second string("babu") according to alphabetical rule
echo $c;

?>
</body>
</html>

Output:-1(for strcmp(str1,str2)will return -1 when the alphabetical position of the first letter of one string(str1) is smaller than the alphabetical position of the first letter of the second string(str2)).

Now We will give an example where two strings are not equal, but the alphabetical position of the first letter of one string("smit") is greater than the alphabetical position of the first letter of the second string("ashok"):

<html>
<body>
<?php
$a="smit";
$b="ashok";
$c=strcmp($a,$b);//here first string>second string according to alphabetical rule
echo $c;

?>
</body>
</html>

output:1(for strcmp(str1,str2)will return 1 when the alphabetical position of the first letter of one string(str1) is greater than the alphabetical position of the first letter of the second string(str2)).

Now we will give another example for using strcmp() function:

<html>
<body>
<?php
$a="aamit";
$b="ashok";
$c=strcmp($a,$b);//here first string<second string according to alphabetical rule
echo $c;

?>
</body>
</html>

Output:-1

How will compare between two strings with case-insensitive way?

There is a predefined function strcasecmp(), which contains two arguments and returns a value on the match.
Now we will give an example for the comparison of two strings "john" and "john" using strcasecmp() function:

<html>
<body>
<?php
$a="john";
$c="john";
$b=strcasecmp($a,$c);//here two strings equal but one is in uppercase and another is in lowercase

echo $b;
?>
</body>
</html>

Output:0