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 :)
Asked
Active
Viewed 1,955 times
-2
-
@Sven I think OP means duplicate letters among both words. – Austin Brunkhorst Feb 18 '13 at 08:06
-
And "b" is not in the output. As long as we do not know the correct output, a solution is a little more complicated... – Sven Feb 18 '13 at 08:13
6 Answers
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
-
thankyou so much sir austin but for now how about counting the remaining non duplicate letters? example: "christine" and "tin" it will only output 6, because of (chrise) thanks again – Christine Javier Feb 18 '13 at 09:15
-
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!
?>