RE: [PHP] How do I do count the occurrence of each word?
| From: | Ford, Mike | Date: | Mon, 20 Aug 2012 10:31:41 +0000 |
| Subject: | RE: [PHP] How do I do count the occurrence of each word? | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-318772@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Marco Behnke [mailto:marco@behnke.biz]
> Sent: 19 August 2012 06:39
> To: php-general@lists.php.net
> Subject: Re: [PHP] How do I do count the occurrence of each word?
>
> Am 19.08.12 06:59, schrieb tamouse mailing lists:
> > On Sat, Aug 18, 2012 at 6:44 PM, John Taylor-Johnston
> > <jt.johnston@usherbrooke.ca> wrote:
> >> I want to parse this text and count the occurrence of each word:
> >>
> >> Sample Output:
> >>
> >> determined = 4
> >> fire = 7
> >> patrol = 3
> >> theft = 6
> >> witness = 1
> >> witnessed = 1
> >>
[...]
> > and then you just run through the words building an associative
> array
> > by incrementing the count of each word as the key to the array:
> >
> > foreach ($words as $word) {
> > $freq[$word]++;
> > }
>
> Please an existence check to avoid incrementing not set array keys
>
> foreach ($words as $word) {
> if (array_key_exists($word, $freq)) {
> $freq[$word] = 1;
> } else {
> $freq[$word]++;
> }
> }
Erm...
$freq = array_count_values($words)
(http://php.net/array_count_values)
Cheers!
Mike
--
Mike Ford,
Electronic Information Developer, Libraries and Learning Innovation,
Portland PD507, City Campus, Leeds Metropolitan University,
Portland Way, LEEDS, LS1 3HE, United Kingdom
E: m.ford@leedsmet.ac.uk T: +44 113 812 4730
To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm