How to Sort and Count Word Instances Efficiently in PHP?

Mary-Kate Olsen
Release: 2024-10-21 11:36:31
Original
335 people have browsed it

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>
Copy after login

This code will output the following array:

Array
(
    [happy] => 4
    [beautiful] => 1
    [lines] => 3
    [pear] => 2
    [gin] => 1
    [rock] => 1
)
Copy after login
  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>
Copy after login

This will result in the following sorted array:

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

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!

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