Page 1 of 1

Occurrences within an array

Posted: Tue May 03, 2005 9:19 am
by Archy
Hi, I'm currently having a small problem in finding out how many times a string occurs in an array - without looping through and testing every element within it.

For instance

Code: Select all

$animals = Array = ('Dog', 'Cat', 'Dog', 'Goldfish', 'Dog', 'Bear', 'Cat');
So, if I did a search for 'Dog', it would return '3', and 'Cat' would return '2'etc.

Any help would be appreciated, thanks,
Archy

Posted: Tue May 03, 2005 10:01 am
by JayBird

Posted: Tue May 03, 2005 10:01 am
by Wayne
have a look at array_count_values()

Posted: Tue May 03, 2005 10:05 am
by Archy
Yes, I saw that prior to coming here, but it just gives you a list, similay to print_r($array);. I looked on PHP.net, but couldnt find anything helpful, and just wondered if anyone had done anything like this before.

Posted: Tue May 03, 2005 10:17 am
by JayBird
Very very simplistic example

Code: Select all

$user_input = "Dog"; //could get value from a form

$animals = Array('Dog', 'Cat', 'Dog', 'Goldfish', 'Dog', 'Bear', 'Cat');

$animal_count = array_count_values($animals);

echo "There are ".$animal_count[$user_input]." occurence of your search";