質問

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 :)

役に立ちましたか?

解決 2

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!';

他のヒント

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
)

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
)
$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);

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

<?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!

?>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top