Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-21 10:26:02
Original
345 people have browsed it

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

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

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

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

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!

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