0

This code below basically will count the number of occurrences of a word inside an array.

What I would like to happen now though, is to get $word, assign it as a key to an array, and assign $WordCount[$word] to be its value. So for example, if I get, a word "jump", it will be automatically assigned as the key of an array, and the number of occurrences of the word "jump" ($WordCount[$word]) will be assigned as its value. Any suggestions please?

function Count($text)
{
    $text = strtoupper($text);
    $WordCount = str_word_count($text, 2);

    foreach($WordCount as $word)
    {   
        $WordCount[$word] = isset($WordCount[$word]) ? $WordCount[$word] + 1 : 1;
        echo "{$word} has occured {$WordCount[$word]} time(s) in the text <br/>";                       
    }
}
1
  • To modify array values inside a foreach, you have to use foreach($WordCount as &$word) Commented Jul 26, 2012 at 0:55

1 Answer 1

1

Try this code:

<?php

$str = 'hello is my favorite word.  hello to you, hello to me.  hello is a good word';

$words = str_word_count($str, 1);

$counts = array();
foreach($words as $word) {
    if (!isset($counts[$word])) $counts[$word] = 0;
    $counts[$word]++;
}

print_r($counts);

Output:

Array
(
    [hello] => 4
    [is] => 2
    [my] => 1
    [favorite] => 1
    [word] => 2
    [to] => 2
    [you] => 1
    [me] => 1
    [a] => 1
    [good] => 1
)

You can't echo the values of the count inside your loop until you have fully grouped all the words together.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @drew010! this is a great help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.