php: sort and count instances of words in a given string
Asked Answered
C

2

17

I need help sorting and counting instances of the words in a string.

Lets say I have a collection on words:

happy beautiful happy lines pear gin happy lines rock happy lines pear

How could I use php to count each instance of every word in the string and output it in a loop:

There are $count instances of $word

So that the above loop would output:

There are 4 instances of happy.

There are 3 instances of lines.

There are 2 instances of gin....

Cribble answered 6/6, 2010 at 15:40 Comment(0)
P
54

Use a combination of str_word_count() and array_count_values():

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

gives

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

The 1 in str_word_count() makes the function return an array of all the found words.

To sort the entries, use arsort() (it preserves keys):

arsort($words);
print_r($words);

Array
(
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [rock] => 1
    [gin] => 1
    [beautiful] => 1
)
Publish answered 6/6, 2010 at 15:47 Comment(3)
How can I use this with an accent word ? Example: ÉpéeVoguish
Amazingly simple! ;) Thanks!Pious
@Pious yes you said well no other answer required to look ;)Ceylon
H
6

Try this:

$words = explode(" ", "happy beautiful happy lines pear gin happy lines rock happy lines pear");
$result = array_combine($words, array_fill(0, count($words), 0));

foreach($words as $word) {
    $result[$word]++;
}

foreach($result as $word => $count) {
    echo "There are $count instances of $word.\n";
}

Result:

There are 4 instances of happy.
There are 1 instances of beautiful.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock. 
Horsefaced answered 6/6, 2010 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.