String Equals in PHP with Example

PHP Program 1:

[php]
$str1 = "Java";
$str2 = "JAVA";
if (strcasecmp($str1, $str2) == 0) {
echo "Both are Equal";
}else{
echo "Both are Not Equal";
}
[/php]

Output:
[plain gutter=”false”]
Both are Equal
[/plain]

See the below program, we are giving the flipkart with space and without space so we are getting “both are not equal”. But if you equal the same to 1 then you will get “both are equal”.

With space and without space strings are not equal:

[php]
$str1 = "flipkart ";
$str2 = "FLIPKART";
if (strcasecmp($str1, $str2) == 0) {
echo "Both are Equal";
}else{
echo "Both are Not Equal";
}
[/php]

Output:
[plain gutter=”false”]
Both are Not Equal
[/plain]

With Space and Without Space Strings are equal:

[php]
$str1 = "flipkart ";
$str2 = "FLIPKART";
if (strcasecmp($str1, $str2) == 1) {
echo "Both are Equal";
}else{
echo "Both are Not Equal";
}
[/php]

Output:
[plain]
Both are Equal
[/plain]

But the above one is not recommnended, so better you can use trim() with equal to 0 only always like below,
Equals After trim() is Recommended Always:

[php]
$str1 = "flipkart ";
$str2 = "FLIPKART";
if (strcasecmp(trim($str1), trim($str2)) == 0) {
echo "Both are Equal";
}else{
echo "Both are Not Equal";
}

[/php]

Output:
[plain]
Both are Equal
[/plain]

Recommended Books:

Leave a Reply