Forum Moderators: coopster

Message Too Old, No Replies

Unable to increment array key's value foreach word instance count.

Trying to count instances of each word in an array.

         

JAB Creations

5:28 am on Nov 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to create an array of keys (words) with values (number of instances of those words). However I can't figure out how to increment the value when a word in the $count array. Here is what I have...

- John

<?php
$text = "trout trout trout lucky";
$pieces = explode(" ",$text);

$count = array();
foreach ($pieces as $key => &$value)
{
if (!in_array($value,$count))
{
$count[$value]='1';
}
else
{
$value++;
}
}
?>

TheMadScientist

5:52 am on Nov 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Do you mean like this:

<?php
$text = "trout trout trout lucky";
$text = explode(" ",$text);
$word_count = array_count_values($text);
print_r($word_count);
?>

JAB Creations

5:59 am on Nov 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Genius! That works perfectly! Thank you very much! :)

I'm still wondering why I can't update an array item's value?

- John

TheMadScientist

6:36 am on Nov 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



1.) I don't see $count defined as anything other than an array, so your comparison is in_array(needle,haystack); or in other words in_array($value,''); which will not ever evaluate to true, because $count is an empty array.

2.) You're using in_array() rather than a str function, and by using foreach() which is basically comparing array pieces, you are switching from an array comparison to a string comparison.

I don't like foreach(), because all the benchmarking I've read says it's about inefficient, but if I was doing it with a foreach() I would do it like this:

<?php
$text = "trout trout trout lucky";
$pieces = explode(" ",$text);

$count=array();
$string='';
foreach ($pieces as $piece)
{
if (strstr($string,$piece))
{
$count[$piece]++;
}
else
{
$string.=" ".$piece;
$count[$piece]=1;
}
}
print_r($count);
?>