String Equals in PHP with Example

String Equals in PHP with Example

PHP Program 1:

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

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:

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

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

With Space and Without Space Strings are equal:

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

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:

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

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

Recommended Books:

1,734 total views, 4 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.