Page 1 of 1

Quick Array challenge

Posted: Wed Sep 10, 2003 3:06 am
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

Posted: Wed Sep 10, 2003 3:29 am
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.

Posted: Wed Sep 10, 2003 3:51 am
by JayBird
Mate, that worked a treat :)

Thanks

Mark

Posted: Wed Sep 10, 2003 4:30 am
by twigletmac
There's also array_count_values().

Mac

Posted: Wed Sep 10, 2003 4:59 am
by JayBird
ah yes Mac, that seem like an easier solution.

Thanks guys and gals

Posted: Fri Sep 12, 2003 12:41 pm
by delorian
Yes, much easier :D - but it took me less time to write it than find the allready opened door.