String Comparison In PHP

What we are going to see through this article is String Comparison In PHP. A comparison operator allows you to compare two values and returns true if the comparison is truthful and false otherwise.

PHP strcmp() is an inbuilt function that compares two strings. The strcmp() function is binary-safe and case-sensitive. The strcmp() function is used to compare two strings. 

Those are:

  • Using == operator,
  • Using strcmp() function.
String Comparison In PHP

String comparison using == vs strcmp() in PHP

String Comparison in PHP

Now, We can use the (== operator) to perform a task here.

<?php

// Declaration of strings
$name1 = "Coding";
$name2 = "Diksha";

// Use == operator
if ($name1 == $name2) {
	echo 'Both strings are equal';
}
else {
	echo 'Both strings are not equal';
}
?>

Output

This is an example output of string comparison in PHP for your reference shown below:

Both strings are not equal

String Comparision in PHP

Below, We can use the strcmp() in-built function to do a task here. The syntax is given below:

strcmp( $string1, $string2 )

Program Code

<?php

// Declaration of strings
$name1 = "Hello";
$name2 = "Hello";

// Use strcmp() function
if (strcmp($name1, $name2) !== 0) {
	echo 'Both strings are not equal';
}
else {
	echo 'Both strings are equal';
}
?

Read Also: PHP Pow() Function

Output

Both the strings are equal

Final Words

What we learned through this article is String Comparison In PHP. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment