Page 1 of 1
Count highest number of occurrences of element in an array
Posted: Tue Apr 13, 2004 7:09 pm
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?
Posted: Tue Apr 13, 2004 7:17 pm
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);
?>
Posted: Tue Apr 13, 2004 7:26 pm
by JAM
Or [php_man]rsort[/php_man] if frequency isn't important
Posted: Tue Apr 13, 2004 7:28 pm
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
)
Posted: Tue Apr 13, 2004 7:33 pm
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... =)
Posted: Tue Apr 13, 2004 7:34 pm
by markl999
I was thinking one thing, wrote another
I feel the knowing, i all that do the time.