Reputation: 61
user 1 writes a word (word1) and I want to count how many letters of the word1 there are within the opponent word (word2).
At first I used the strpos
function but it doesn't seem to count reppeated letters so I change to the str_word_count
function but no matter what the word1 is the countex
is always 5
This is my code:
for($i=0;$i<10 && ($rowword=mysqli_fetch_assoc($result)) ;$i++){
$aword1 = str_split($rowword['word']);
$word2=$row['word2']; //$row comes from another query that gets the word of the opponent
$countex=0;
for($i=0;$i<5;$i++){
$currentletter=$aword1[$i];
if(str_word_count($word2,0,$currentletter)){
$countex++;
}
}
} //end of outter for
Can someone tell me what is the problem?
Example of what I want to achieve:
word2=annoy, word1=again
in this example countex
should be 2 because in the word "again" the letter "a" and "n" exist in the word "annoy"
Upvotes: 0
Views: 49
Reputation: 6379
You can use str_split
aswell as strpos
for that:
<?php
$word1 = 'abcdefghijkl';
$word2 = 'acgikluuo';
$expected = 6;
function countMatchingChars($word1, $word2) {
$matching = 0;
foreach(str_split($word1) as $char) {
if(strpos($word2, $char) !== false) {
$matching++;
}
}
return $matching;
}
$matchingChars = countMatchingChars($word1, $word2);
assert($matchingChars === $expected);
References:
Upvotes: 0
Reputation: 178
If you want to know how many letters are in both words then you can use this code:
$lettersFromWord1 = str_split ($word1);
$lettersFromWord2 = str_split ($word2);
$matches = 0;
foreach($lettersFromWord1 as $letter){
if ( in_array($letter, $lettersFromWord2)){
$matches++;
}
}
echo "Word: " . $word1 . " and Word: " . $word2 . " has " . $matches . " matching letters";
Upvotes: 1