tags:

views:

73

answers:

4

I have an array of ids like 127415157,31323794... (range not known). What is the quickest way to find the max frequency ID in PHP?

$array_ids = array()
A: 

Try max

$max = max($array_ids);
Salil
I don't think this addresses the OP's question - they seem to be dealing with *frequencies*, and thus I'm guessing they want the item that occurs most often in the array.
Amber
@Dav: you are right
Bruce
+5  A: 
// Gives us an associative array of id=>count mappings,
$counts = array_count_values($array_ids);
// and sorts it from largest to smallest count
arsort($counts);

// Gets the first key after sorting, which is the id with the largest count
$max_freq_id = key($counts);

stereofrog's suggestion of using array_search() combined with max() may be faster than this, however, since it doesn't need to completely sort the array, and thus will run in O(n) time instead of O(n log n).

Amber
unfortunately, you cannot apply 'sort' and friends to expressions.
stereofrog
Right, forgot that PHP's sorts do so in-place. Fixed.
Amber
+5  A: 
$a = array(1, 2, 3, 4, 3, 3, 4, 4, 1, 3);
$r = array_count_values($a);
$k = array_search(max($r), $r);
echo "most frequent value is $k";
stereofrog
+1, since this is most likely faster than the original solution I proposed, given that searching for the max takes linear time as opposed to sorting which takes `n log n` time.
Amber
yeah looks great
nik
@stereo: Shouldn't we use array_keys instead of array_search?
Bruce
@Bruce - array_search returns a key, which is the most frequent value we're searching for
stereofrog
@stereofrog: but there can be multiple elements with the same frequency. anyway it was a trivial observation
Bruce
+1  A: 

Addressing the issue of multiple elements with same frequency:

$values = array(1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6); 
$freq   = array_count_values($values);
arsort($freq);
$max = $val = key($freq); 
while(next($freq) && current($freq) == $freq[$max]){
    $val .= ','.key($freq);
}

echo " most frequent value is/are $val ";

this will ouput

most frequent value is/are 5,3

also, it's a little faster than using array_search and max combo...

acmatos