Home >Backend Development >PHP Tutorial >How to Count and Sort Unique Word Instances in a String with PHP?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-21 12:09:30857browse

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:

  1. Count Word Occurrences: Utilize the array_count_values() function in conjunction with str_word_count(). The latter function parses the input string into an array of words, with each unique word serving as an array key. The count of each word is determined by its corresponding array value.
<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>
  1. Sort Word Occurrences: To display the word counts in descending order, employ the arsort() function. This function arranges the array elements in descending order while preserving their keys (i.e., the word values).
<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!

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