Mobin Faraji Mobin Faraji - 3 months ago 12
PHP Question

make in order the most repeated words in a text file

Sorry for my bad English.
I have a file called searches.txt and it contacins this(for example);


flower
google
rose
flower
rose
rose
flower
flower


As you see, ((flower)) is the most repeated word and then ((rose)) and then ((google)) is.
I want to show it like this:


1-flower
2-rose
3-google


I want a php function that do this.
Again sorry for my bad English

Answer

Not very difficult, but I had nothing else to do:

$string = 'flower google rose flower rose rose flower flower';

$words = explode(' ', $string);

$tmp = array_count_values($words);;

asort($tmp);

// To show the 'word': 'count'
foreach ($tmp as $word => $count)
{
    echo $word . ': ' . $count . '<br>';
}

// To show the placements
$placement = 0;
foreach ($tmp as $word => $count)
{
    $placement++;
    echo $placement . ': ' . $word;
}