I need to find/calculate 1 word from a list of 20 words with following conditions:
- If longest word in array is 5 characters then result will be 5 char. (Word I am looking for will always be 4, 5 or 6 chars long.)
- Count/recognise every char and its position in word for later calculation.
- Words in array contains uppercase letters A-Z and/or digits 0-9.
Here is the 20 words I have:
$words = array( 'MVW',
'MWAH',
'MWAH',
'MYW',
'MW',
'MY9AH',
'MYQAH',
'MYQAH',
'MY9AH',
'MYQAH',
'MYQAH',
'MWAH',
'MYQAH',
'MYSWI',
'MYQAH',
'MYQAH',
'MW',
'MW',
'MW',
'MW');
I need to count chars in row and find higest occurency of char to get this result:
1. char is: M - occurred 20 times as 1. character in words.
2. char is: Y - 11 times.
3. char is: Q - 7 times.
4. char is: A - 10 times.
5. char is: H - 9 times.
Result from Array $words I want is: MYQAH
I have tried this code:
<?php
$words = array( 'MVW',
'MWAH',
'MWAH',
'MYW',
'MW',
'MY9AH',
'MYQAH',
'MYQAH',
'MY9AH',
'MYQAH',
'MYQAH',
'MWAH',
'MYQAH',
'MYSWI',
'MYQAH',
'MYQAH',
'MW',
'MW',
'MW',
'MW');
$newarray = array();
$cc2 = 0;
$cc3 = 0;
$cc4 = 0;
$cc5 = 0;
$cc6 = 0;
foreach($words as $run) {
if (isset($run['1']) && !isset($run['2'])) {
$newarray[] = array($run['0'],$run['1']);
$cc2++;
}
if (isset($run['2']) && !isset($run['3'])) {
$newarray[] = array($run['0'],$run['1'],$run['2']);
$cc3++;
}
if (isset($run['3']) && !isset($run['4'])) {
$newarray[] = array($run['0'],$run['1'],$run['2'],$run['3']);
$cc4++;
}
if (isset($run['4']) && !isset($run['5'])) {
$newarray[] = array($run['0'],$run['1'],$run['2'],$run['3'],$run['4']);
$cc5++;
}
if (isset($run['5']) && !isset($run['6'])) {
$newarray[] = array($run['0'],$run['1'],$run['2'],$run['3'],$run['4'],$run['5']);
$cc6++;
}
}
echo "Length / Found words<br>\n";
echo "2 chars / $cc2<br>\n";
echo "3 chars / $cc3<br>\n";
echo "4 chars / $cc4<br>\n";
echo "5 chars / $cc5<br>\n";
echo "6 chars / $cc6<br>\n";
echo "<pre>";
var_dump($newarray);
echo "</pre>";
?>
And I get this results:
Length / Found words
2 chars / 5
3 chars / 2
4 chars / 3
5 chars / 10
6 chars / 0
array(20) {
[0]=>
array(3) {
[0]=>
string(1) "M"
[1]=>
string(1) "V"
[2]=>
string(1) "W"
}
[1]=>
array(4) {
[0]=>
string(1) "M"
[1]=>
string(1) "W"
[2]=>
string(1) "A"
[3]=>
string(1) "H"
}
[2]=>
array(4) {
[0]=>
string(1) "M"
[1]=>
string(1) "W"
[2]=>
string(1) "A"
[3]=>
string(1) "H"
}
[3]=>
array(3) {
[0]=>
string(1) "M"
[1]=>
string(1) "Y"
[2]=>
string(1) "W"
}
[4]=>
array(2) {
[0]=>
string(1) "M"
[1]=>
string(1) "W"
}
[5]=>
array(5) {
[0]=>
string(1) "M"
[1]=>
string(1) "Y"
[2]=>
string(1) "9"
[3]=>
string(1) "A"
[4]=>
string(1) "H"
}
[6]=>
array(5) {
[0]=>
string(1) "M"
.........
Question: What would be the best way to get result: MYQAH
from the words above in array?
Thank you so much for helping.