PHP Echo Tutorials

String Comparison Operations in PHP

Written by phpecho.com   

In this short PHP tutorial, we will cover the most basic of string operations - comparison of two strings. This is one of the most basic functionalities that you will need to use multiple times in any program that you write. Since any program depends on conditional statements, if the comparator operators are not understood properly, then the chances are the program would not function as expected.

We will cover three different comparison operators - double equal, strcmp and strcasecmp. Let us get started.

Consider the following string (I know there is nothing exciting about this valueSmile)

Hello World To All PHP Programmers

We will use the above example to try out all our functions.

There are two simple ways to compare two strings. The first is the '==' operator. This tells us if two strings have the same sequence of the same characters.

If it has, it returns true otherwise false. Consider the example below:

$stringOne = "Hello World To All PHP Programmers";
$stringTwo = "Hello World To All PHP Programmers";
$stringThree = "Hello World To All PHP & mySQL Programmers";
if ($stringOne == $stringTwo){
printf ("Equal");
} else {
printf ("Not Equal");
}
if ($stringTwo == $stringThree){
printf ("Equal");
} else {
printf ("Not Equal");
}

If the code snippet above is executed, then the output will be as follows:

Equal
Not Equal

The double equals operator is trustworthy only if no type conversion has been done and both the arguments are strings.

Another basic string comparison function is strcmp(). This function takes two strings and compares them byte by byte till it finds a difference. It returns 0 if both strings are equal. In our example, we will use the strcmp() function as follows:

if (strcmp($stringOne,$stringTwo) == 0){
printf("Equal");
} else {
printf("Not Equal");
}
if (strcmp($stringTwo,$stringThree) == 0){
printf("Equal");
} else {
printf("Not Equal");
}

The output for this code snippet will also be the same.

strcmp() function is case sensitive. It means that the function will infer "Hi" to be different from "hi". In case, you need to ignore the case while comparing strings, you should use strcasecmp(). This works exactly in a similar way to strcmp() except that it is case insensitive.