How to Sort and Count Word Instances in a PHP String?

Barbara Streisand
Release: 2024-10-21 10:37:29
Original
560 people have browsed it

How to Sort and Count Word Instances in a PHP String?

Sorting and Counting Word Instances in a String in PHP

Sorting and counting occurrences of words in a string is a common task in programming. Fortunately, PHP provides a simple and elegant solution for this problem.

Using str_word_count() and array_count_values()

The str_word_count() function returns an array of all words in a string, while the array_count_values() function counts the number of occurrences of each element in an array. By combining these two functions, we can efficiently count the instances of each word in a string.

<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));</code>
Copy after login

The resulting array, $words, will contain the count of each unique word in $str.

Sorting the Entries

To sort the word counts, we can use the arsort() function, which sorts an array in descending order while preserving the keys.

<code class="php">arsort($words);</code>
Copy after login

This will sort the $words array by the count of each word, with the most frequently occurring word at the beginning of the array.

Printing the Results

Finally, we can loop through the $words array and print the count of each word:

<code class="php">foreach ($words as $word => $count) {
    echo "There are $count instances of $word.<br>";
}</code>
Copy after login

This code will output the following:

There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of gin.
There are 1 instance of pear.
There are 1 instance of rock.
There are 1 instance of beautiful.
Copy after login

Additional Notes

The 1 argument passed to str_word_count() indicates that it should return an array of all words, rather than a string.

Sorting the entries is optional, but it can be useful for displaying the data in a more meaningful way.

This solution can be easily adapted to handle other types of strings, such as sentences or paragraphs.

The above is the detailed content of How to Sort and Count Word Instances in a PHP String?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!