String comparison is one of the most important part of strings related coding that you might do in your projects. It's very easy to understand but you will have to remember some key differences when using comparison operators while comparing strings.
As usual we will begin with an example but in this case I will include 2 different examples in one set to show you the difference in output of comparison when using different comparison operators.
<?php //Example 1 with '==' comparison operator
$a = 0;
if ($a == "Zero") {
echo 'True';
}
else {
echo 'False';
}
?>
<?php //Example 2 with '===' comparison operator
$a = 0;
if ($a === "Zero") {
echo 'True';
}
else {
echo 'False';
}
?>
<?php
$test = NULL;
if ($test == 0) {
echo 'errrr';
}
else {
echo 'hmm';
}
?>
<?php
$test = NULL;
if ($test == '0') {
echo 'errrr';
}
else {
echo 'hmm';
}
?>
<?php
$test = '';
if ($test == 0) {
echo 'errrr';
}
else {
echo 'hmm';
}
?>
<?php
$test = '';
if ($test == '0') {
echo 'errrr';
}
else {
echo 'hmm';
}
?>
Above, in example #1, I have used '==' operator, which is evaluating if the value on right hand side is equal to value on left hand side. I guess, you expected the output to be 'False'? No, that's not the case. The output is 'True'. Strange? Not really!
Always remember, when comparing strings, you should use '===' operator (strict comparison) and NOT '==' operator (loose comparison). When comparing an integer with a string, the string is converted to a number. And if you compare two numerical strings, they are compared as integers. Now try to replace $a == "Zero" with $a == "00" in the first example and see the results.
Using built-in function to compare - strcmp()
One other way of doing string comparison is using the PHP built-in function called strcmp(). This comparison is case-sensitive and the syntax of this function is:
strcmp ( string str1, string str2 )
It will return the following after comparison and your further processing should be based on this output:
Returns < 0 if str1 is less than str2
Returns > 0 if str1 is greater than str2
Returns 0 if they are equal
Refer to the example below to see usage of strcmp():
<?php
$a = "First";
$b = "Second";
$c = "Third";
$str = "Third"; //Third with a capital 'T'
$str1 = "third"; //third with a small 't'
$d = strcmp($a,$b); //storing the output of strcmp in $d
echo $d; //Output: -1 ($a is less than $b)
$d = strcmp($b,$c);
echo $d; //Output: -1 ($b is less than $c)
$d = strcmp($c,$str);
echo $d; //Output: 0 ($c and $str are equal)
$d = strcmp($str,$str1); //Comparing third with Third
echo $d; //Output: -1 ($str is less than $str1)
//Another usage is
if (strcmp($c, $str) == 0) {
echo "strings are equal";
}
else {
echo "string are not equal";
}
?>
For case-insensitive comparison use the strcasecmp() function instead. Just replace the function name in above example and test the results.
No comments:
Post a Comment