Compare Two Strings using a Loop

One way to compare two strings is by iterating through each character and comparing them individually.

PHP




<?php
  
function compareStrings($str1, $str2) {
    if (strlen($str1) != strlen($str2)) {
        return false;
    }
  
    for ($i = 0; $i < strlen($str1); $i++) {
        if ($str1[$i] != $str2[$i]) {
            return false;
        }
    }
    return true;
}
  
// Driver code
$str1 = "hello";
$str2 = "hello";
  
if (compareStrings($str1, $str2)) {
    echo "The strings are equal.";
} else {
    echo "The strings are not equal.";
}
  
?>


Output

The strings are equal.


Explanation:

  • The compareStrings function first checks if the lengths of the two strings are equal. If not, the strings are not equal.
  • It then iterates through each character of the strings and compares them. If any characters are different, the function returns false.
  • If all characters are the same, the function returns true.

How to Compare Two Strings without using strcmp() function in PHP ?

Comparing two strings is a common operation in programming. In PHP, the strcmp() function is typically used to compare two strings. However, there may be situations where you need to compare strings without using this built-in function, such as for learning purposes or to meet specific constraints. In this article, we will explore different approaches to comparing two strings in PHP without using the strcmp() function.

Table of Content

  • Compare Two Strings using a Loop
  • Compare Two Strings using Array Functions
  • Compare Two Strings using a Hashing Function
  • Compare Two Strings ising implode() and aray_map() Functions

Similar Reads

Compare Two Strings using a Loop

One way to compare two strings is by iterating through each character and comparing them individually....

Compare Two Strings using Array Functions

...

Compare Two Strings using a Hashing Function

Another approach is to convert the strings to arrays and use array functions to compare them....

Compare Two Strings ising implode() and aray_map() Functions

...