Home >Backend Development >PHP Tutorial >How to Count and Sort Unique Word Instances in a String with PHP?
Sorting and Counting Word Instances in a String Using PHP
In various programming tasks, it becomes necessary to efficiently manage and count word occurrences within a given string. For instance, consider the following text:
happy beautiful happy lines pear gin happy lines rock happy lines pear
Challenge: Count the occurrences of each word in the provided string and display the results in a loop, highlighting the word count.
Solution: Leverage PHP's built-in string manipulation functions to achieve this task:
<code class="php">$str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear '; $words = array_count_values(str_word_count($str, 1)); print_r($words);</code>
<code class="php">arsort($words); print_r($words);</code>
Output:
Array ( [happy] => 4 [lines] => 3 [pear] => 2 [rock] => 1 [gin] => 1 [beautiful] => 1 )
This approach effectively counts and sorts the word occurrences, allowing for efficient manipulation and display of word-frequency data.
The above is the detailed content of How to Count and Sort Unique Word Instances in a String with PHP?. For more information, please follow other related articles on the PHP Chinese website!