"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort and Count Word Instances Efficiently in PHP?

How to Sort and Count Word Instances Efficiently in PHP?

Published on 2024-11-09
Browse:308

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:
$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);

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:
arsort($words);
print_r($words);

This will result in the following sorted array:

Array
(
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [rock] => 1
    [gin] => 1
    [beautiful] => 1
)
Release Statement This article is reprinted at: 1729475057 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3