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

In this section, compare two strings using the implode() and array_map() functions in PHP. Steps to compare two strings:

  • Convert each string into an array of characters using str_split() function.
  • Use array_map() function to compare each corresponding character in the two arrays.
  • Use implode() function to concatenate the results of the comparison into a single string.
  • Check if the resulting string contains only “1” (which indicates that all characters are equal) to determine if the two strings are the same.

PHP




<?php
  
function compareStr($str1, $str2) {
    $arr1 = str_split($str1);
    $arr2 = str_split($str2);
  
    $result = array_map(function($char1, $char2) {
        return $char1 === $char2 ? '1' : '0';
    }, $arr1, $arr2);
  
    $comparisonResult = implode('', $result);
  
    return strpos($comparisonResult, '0') === false;
}
  
// Driver code
$str1 = "Geeks";
$str2 = "Geeks";
$str3 = "Hello";
  
echo (compareStr($str1, $str2) ? "Equal" : "Not Equal") . "\n";
echo compareStr($str1, $str3) ? "Equal" : "Not Equal";
  
?>


Output

Equal
Not Equal

In this program, the compareStr() function takes two strings as input and returns true if they are equal and false otherwise.



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

...