I have a solution, which compares 2 given strings and returns the number of total matching characters.

I know I haven't initialized the variables and arrays and that this (correctly) yields warnings. I know the variables aren't self-explanatory as they should be.

function commonCharacterCount($s1, $s2) {
    $a = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
    $b = (strlen($s1) > strlen($s2)) ? $s1 : $s2;

    foreach(count_chars($a, 1) as $i => $v) {
        $c[chr($i)] = $v;

    foreach (count_chars($b, 1) as $i => $v) {
        $d[chr($i)] = $v;

    $t = 0;
    foreach($c as $k => $v) {
        if($c[$k] <= $d[$k]) {
            $t += $c[$k];
        } else {
            $t += $d[$k];
    return $t;

For instance, I have the two strings:

$s1 = "abacadeee"; and $s2 = "aabbccddee";, the expected output would be 7.

As required, this solution works so far and you can test it here: sandbox

Which steps are unnecessary and how can I improve this algorithm?

  • 1
    \$\begingroup\$ what is the logic of common character count? from you test data characters that matches are a, b, c, d, e = 5. Again if I count occurrence the value is not 7. or even i count maximum occurrence the value is not 7 \$\endgroup\$ Commented Mar 14, 2019 at 15:22

1 Answer 1


I would recommend a process like this:

Code: (Demo)

$string1 = "abacadeee";
$string2 = "aabbccddee";

$counts2 = count_chars($string2, 1);

$tally = 0;
foreach (array_intersect_key(count_chars($string1, 1), $counts2) as $charcode1 => $count1) {
    $tally += min($counts2[$charcode1], $count1);
echo $tally;

count_chars() lends itself beautifully to this task, so using array functions onward is a sensible choice.

It is important to try to minimize iterations and not perform any useless iterations. By calling array_intersect_key() on the two count_chars() results, the foreach() loop is only going to iterate elements with keys which are shared between the two arrays. In doing this, you don't need to check which array is smaller (which is otherwise how you would choose which array to iterate).

$tally is incremented by the lesser of the two counts for each char.

p.s. calling chr() is irrelevant to your objective.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.