-2

hi there i'm a newbie in php and i would like to ask how to write a code that will out put the number of duplicated letters in two words. for example: "apple" and "ball" in overall it has a 7 same letters (a,a,p,p,l,l,l) thank you in advance :)

Christine Javier
  • 31
  • 1
  • 2
  • 6

6 Answers6

2

Not the most efficient but arguably simple:

$word1 = "apple";
$word2 = "ball";
print_r(array_count_values(str_split($word1.$word2)));

Output:

Array
(
    [a] => 2
    [p] => 2
    [l] => 3
    [e] => 1
    [b] => 1
)
user703016
  • 37,307
  • 8
  • 87
  • 112
1

You can do something like this.

$a = 'apple';
$b = 'ball';

$duplicates = array_count_values(array_merge(str_split($a), str_split($b)));

// Array ( [a] => 2 [p] => 2 [l] => 3 [e] => 1 [b] => 1 )
print_r($duplicates);

If you want to get the total number of matches among the words, you could then do this.

$totalMatches = 0;

foreach($duplicates as $count) {
    if($count > 1)
        $totalMatches += $count;
}

// 7 matches!
echo $totalMatches . ' matches!';
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
1

may be this:

$a= "apple";
$a.=  "ball";
print_r(array_count_values(str_split($a)));

Output:

Array
(
    [a] => 2
    [p] => 2
    [l] => 3
    [e] => 1
    [b] => 1
)
Engineer
  • 5,911
  • 4
  • 31
  • 58
1
$str1   = "apple";
$ar1    = str_split($str1);

$str2   = "ball";
$ar2    = str_split($str2);

$res    = array_merge($ar1,$ar2);
$count  = array_count_values($res);

print_r($count);
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

Try str_split to make array from string and then compare array itself and other for duplicate entry.

kuldeep.kamboj
  • 2,566
  • 3
  • 26
  • 63
0
<?php

$str1 = 'applle';
$str2 = 'ball';
$str1arr = str_split($str1);
$str2arr = str_split($str2);
$all = array_merge($str1arr, $str2arr);
$countall = count($all) - count(array_intersect($str1arr, $str2arr));
echo "count of similar charactors (overall) =".($countall);//7!

?>