user1242749
user1242749

Reputation: 119

creating an array whose key and value is defined

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/>";                       
    }
}

Upvotes: 0

Views: 44

Answers (1)

drew010
drew010

Reputation: 69927

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.

Upvotes: 1

Related Questions