novex novex - 5 months ago 11
PHP Question

Count how many unique characters two strings share with each other

I have written a PHP function that takes two strings as parameters

$str1
and
$str2
.

Now I want to count how many unique characters those two strings share. So for example:

$str1 = "stringstring1";
$str2 = "stringstring2";


In this example they share 6 unique characters, which are:
s,t,r,i,n,g
.

So here is my current code:

<?php

function compare($str1, $str2){
$cmp = 0;

for($i = 0; $i < strlen($str1); $i++){

for($j = 0; $j < strlen($str2); $j++){
if($str1[$i] == $str2[$j])
$cmp++;
}

}

echo "Number of characters in common: ".$cmp."<br />";
}

compare("stringstring1", "stringstring2");

?>


Right now the problem is that it gives me the output 24 instead of 6. And I don't see where I went wrong, that it outputs 24 instead of 6?

Answer

A possible solution is to store the characters in an array which both strings share and then check if you already counted a character before you increment $cmp.

Here is the rewritten code:

function compare($str1, $str2){
    $cmp = 0;
    $used_letter = array();

    for($i = 0; $i < strlen($str1); $i++){

        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]) 
                if(!in_array($str1[$i], $used_letter)){
                    $cmp++;
                    $used_letter[$cmp] = $str1[$i];
                }
        }
    }

    echo "Number of characters in common: " . $cmp . "<br />";

}

compare("stringstring1","stringstring2");
Comments