Count highest number of occurrences of element in 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Count highest number of occurrences of element in an array

Post by Chris Corbyn »

Is there a way to find out which element in an array occurs most often?

For example

Code: Select all

$array = array(1, 2, 3, 3, 3, 4, 5, 6);
"3" occurs more often than 1, 2, 4, 5, or 6 so is there any way php can tell you this. Or even place in order how often elements occur?
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

See array_count_values

Here's a more complete example that produces an array in order of 'frequency'

Code: Select all

<?php
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6);
$ordered = array_count_values($array);
arsort($ordered);
print_r($ordered);
?>
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Or [php_man]rsort[/php_man] if frequency isn't important
Last edited by JAM on Tue Apr 13, 2004 7:31 pm, edited 1 time in total.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

The problem with rsort is that it won't show you the numbers, just the frequency that they occur.
Eg rsort output would be:
Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 1
[4] => 1
[5] => 1
)
and arsort output would be:
Array
(
[4] => 3
[1] => 3
[3] => 3
[6] => 1
[5] => 1
[2] => 1
)
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Yes true, I was thinking one thing, wrote another.

The thought was that (taking your example) $ordered[0] will always give your the highest number, and so on. Might be easier if you do not actually need the frequency...

Edited my post to clarify... =)
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

I was thinking one thing, wrote another
I feel the knowing, i all that do the time.
Post Reply