Open In App

PHP Program to Check if Two Strings are Same or Not

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings, the task is to check whether two strings are same or not in PHP. In this article, we will be looking at different approaches to check two strings are same or not.

Examples:

Input: str1 = "Geeks", str2 = "Geeks"
Output: Both Strings are the same 

Input: str1 = "Hello", str2 = "Geeks"
Output: Both Strings are not same 

Below are the approaches to check if two strings are same or not using PHP:

Using Comparison ‘=’ Operator

The simplest way to check if two strings are the same in PHP is by using the equality comparison operator (==). This operator compares the values of two strings and returns true if they are equal, and false otherwise.

Note: We can also use strict comparison operator (===) to perform the same operation.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
  
$str1 = "Geeks";
$str2 = "Geeks";

if ($str1 == $str2) {
    echo "Both strings are the same.";
} else {
    echo "Both strings are not the same.";
}

?>

Output
Both strings are the same.

Using strcmp( ) Function

The strcmp( ) function compares two strings. It is case-sensitive and returns 0 if the strings are equal, a negative number if the first string is smaller than the second, and a positive number if the first string is greater than the second.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
  
$str1 = "Hello";
$str2 = "Geeks";

if (strcmp($str1, $str2) == 0) {
    echo "Both strings are the same.";
} else {
    echo "Both strings are not the same.";
}

?>

Output
Both strings are not the same.

Using strcasecmp( ) Function

The strcasecmp( ) function compares two strings in a case-insensitive manner. This function works similarly to strcmp( ) but does not consider the case(lower or upper) of the characters.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
  
$str1 = "Hello Geeks";
$str2 = "hello geek";

if (strcasecmp($str1, $str2) == 0) {
    echo "Both strings are the same (case-insensitive).";
} else {
    echo "Both strings are not the same (case-insensitive).";
}

?>

Output
Both strings are not the same (case-insensitive).

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads