Occurrences within an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

Occurrences within an array

Post 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
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post by Wayne »

have a look at array_count_values()
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

Post 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.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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";
Post Reply