-2

Suppose we have two strings and I want to compare them character by character to check if any characters of string a and string b match or not?

An example:

$a = "Hello";  
$b = "world";  

In the above 'o' exists in both strings , so the algorithm should echo exist.

Nico Haase
  • 9,476
  • 35
  • 35
  • 57
Meiji
  • 107
  • 1
  • 11

2 Answers2

5

If you split the strings and remove the duplicates with array_unique, then array_intersect will give you characters that is in both strings.

$a = "Hello";
$b = "world";

$matching = array_unique(array_intersect(str_split(strtolower($a)), str_split(strtolower($b))));
if(count($matching)>0) echo "matching characters: " . implode(", ", $matching); 
//matching characters: l, o

added strtolower as suggested by Ron.

Andreas
  • 23,304
  • 5
  • 28
  • 61
  • I would also implement `strtolower` since `L` and `l` are the same in an alphabet. – Ron van der Heijden Aug 07 '18 at 10:34
  • if the purpose is only to print something when there is a match ,i think you could remove the step of array_unique which increase the time complexity.But if you want to know the matching characters too ,then this answer is great... – Elementary Aug 07 '18 at 10:46
  • @Elementary true. Another thing that makes the same result but faster is moving the array_unique to wrap the array_intersect means you only "unique" the intersected values which is less than 2x input strings. I think I will edit to do that instead – Andreas Aug 07 '18 at 11:01
  • i was thinking ... we can also write ` if($matching) echo "matching characters" .implode(", ",$matching);` to make code evaluation more fast... – Elementary Aug 07 '18 at 11:21
  • @Elementary I didn't think it would make that much difference. I actually thought without count would be slower due to type casting. But you are right, it's a lot faster actually. https://3v4l.org/Vfg6J Ok... something it not correct. I swapped order of them and the result is the opposite. https://3v4l.org/H0sjA – Andreas Aug 07 '18 at 11:34
  • test them separately show the difference @Andreas ...But online the result will always be a little biased.However good job. – Elementary Aug 07 '18 at 13:39
1

You could transform your strings using str_split() and get the matching characters with array_intersect():

$a = "Hello";
$b = "world";

$matching_chars = array_intersect(
    str_split($a),
    str_split($b)
);

if (empty($matching_chars)) {
    echo 'exist';
}

$matching_chars will be an array containing the letters l & o:

Array
(
    [2] => l
    [3] => l
    [4] => o
)
AymDev
  • 5,278
  • 2
  • 28
  • 46