I need help sorting and counting instances of the words in a string.
Lets say I have a collection on words:
happy beautiful happy lines pear gin happy lines rock happy lines pear
How could I use php to count each instance of every word in the string and output it in a loop:
There are $count instances of $word
So that the above loop would output:
There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of gin….
Use a combination of
str_word_count()andarray_count_values():gives
The
1instr_word_count()makes the function return an array of all the found words.To sort the entries, use
arsort()(it preserves keys):