Home  >  Article  >  Backend Development  >  How to Sort and Count Word Instances Efficiently in PHP?

How to Sort and Count Word Instances Efficiently in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 11:36:31248browse

How to Sort and Count Word Instances Efficiently in PHP?

Sorting and Counting Word Instances in a String with PHP

To sort and count instances of words in a given string in PHP, consider leveraging the following techniques:

  1. Determine Word Distribution: Utilize the str_word_count() function to extract an array of words from the input string. Pass '1' as the second parameter to obtain individual words instead of a count.
  2. Count Occurrences: Use array_count_values() to determine the frequency of each word in the resulting array. This will provide you with an associative array where the keys represent words, and the values represent their respective counts.
  3. Example Implementation: Consider the following PHP code snippet as an example:
<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>

This code will output the following array:

Array
(
    [happy] => 4
    [beautiful] => 1
    [lines] => 3
    [pear] => 2
    [gin] => 1
    [rock] => 1
)
  1. Sorting Entries (Optional): To sort the array based on word frequency, you can utilize arsort(), which will preserve the array's keys. For instance:
<code class="php">arsort($words);
print_r($words);</code>

This will result in the following sorted array:

Array
(
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [rock] => 1
    [gin] => 1
    [beautiful] => 1
)

The above is the detailed content of How to Sort and Count Word Instances Efficiently 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