Ok, so as I’m getting my hands dirty with PHP I’ve started playing around with arrays, strings and the like.
Now I know that arrays have a neat feature called “array_count_values” which can help to determine what the most repeated entry is. I wasn’t able to find a string equivalent for this- will I need to convert the string to an array?
Basically, I want my code to determine what the most common (repeated) word is over a certain length in a given string.
Sans the character length qualification, this code can find the answer to the question of what is the most repeated word in an array:
<?php
$param[0]="Ted";
$param[1]="Mark";
$param[2]="Mark";
$param[3]="Ross";
$param[3]="Clarence";
function array_most_common($arr)
{
$counted = array_count_values($arr);
arsort($counted);
return(key($counted));
}
$mostCommon = array_most_common($param);
echo $mostCommon;
?>
So what would make this doable with a string? And a character amount filter?
With a string, you can just
explode()orpreg_split()on space to form an array. Usingpreg_split()is favorable as it will eliminate duplicate and extraneous whitespace thatexplode()will not.Then, once you have an array, use
array_filter()to remove those that don’t meet the character requirements:Once you have the
$filteredarray, just use that inarray_count_values().Here is a demo, which prints: