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:

Both are Equal

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:

Both are Not Equal

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:

Both are Equal

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:

Both are Equal

Recommended Books:

1,212 total views, 1 views today

Leave a Reply

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