Quick Array challenge

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

Quick Array challenge

Post by JayBird »

Arrays are not really my forte, so i'm calling on a little help.

I have an Array called $who_sorted.

This Array could contain something like:

Mark
Mark
Mark
Claire
Claire
Sean
Claire
Mark
Sean
Sean
Sean

Now, what i need to do is count how many times each name occurs in the Array bearing in mind i don't know what names are going to be in it.

Any ideas?

Thanks

Mark
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

Code: Select all

sort($array); // your array should be sorted first
$tmp = null; // actual name
$count = array(); // how many 

foreach($array as $val) {
 if($tmp!=$val) $tmp=$val; // actual counting name
  $count[$tmp]++; // count the name
}
That should do the trick, I think.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Mate, that worked a treat :)

Thanks

Mark
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

There's also array_count_values().

Mac
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

ah yes Mac, that seem like an easier solution.

Thanks guys and gals
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

Yes, much easier :D - but it took me less time to write it than find the allready opened door.
Post Reply