Re: Counting the occurences of items in an array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



From the manual:

array array_count_values ( array input)

array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

Example 1. array_count_values() example
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The printout of the above program will be:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Dotan Cohen wrote:
Has this wheel been invented, but simpler? I've an array of words that
I'd like to know how many occurences of each there are. For instance:
$fruits = array(
   "lemon",
   "orange",
   "banana",
   "apple",
   "orange",
   "banana",
   "orange"    );

And I'd like to create this:
$fruit_count = array(
   "lemon" => 1,
   "orange" => 3,
   "banana" => 2,
   "apple" => 1    );

My current plan of action is to create $fruit_count, and check if
$fruits[0] is listed in it. If not, then I'll add it with a value of
1. If it is already listed then I'll just increase it's number. Ditto
for $fruits[1] and so on...

Has someone cleverer than myself found a better way of doing this?
This function will be used as a word count for text documents, and
some of them have over 5000 words. So if there's a better way of doing
this I'd love to know. Thanks.

Dotan Cohen

http://what-is-what.com/what_is/html_email.html
http://lyricslist.com/lyrics/artist_albums/162/disturbed.php


--

_____________________
Myron Turner
http://www.room535.org
http://www.bstatzero.org
http://www.mturner.org/XML_PullParser/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux