Home  >  Article  >  Backend Development  >  How to Count and Sort Word Occurrences in a String in PHP?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-21 10:26:02230browse

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

Sorting and Counting Word Occurrences in a String

Problem Statement:

You are presented with a string containing various words. The task at hand is to determine the frequency of each word in the string and display it in an organized manner.

Solution Using PHP's Word Counting Function:

PHP provides the str_word_count() function, which splits a string into an array of individual words. By using this function in conjunction with the array_count_values() function, we can effectively count the occurrences of each word.

<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>

The str_word_count() function with the 1 parameter ensures that an array of words is returned. Subsequently, array_count_values() takes this array and converts it into an associative array, where each unique word serves as a key, and its value represents the number of occurrences.

This associative array can be sorted using the arsort() function to list the words in descending order of their frequencies:

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

To display the sorted results in a loop, we can iterate over the sorted array and print the count of each word:

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

This will produce an output similar to the one you provided:

There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock.
There are 1 instances of beautiful.

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

Statement:
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