Log in

View Full Version : Resolved frequency in array



ggalan
05-05-2012, 03:36 AM
i have the following code which gets the MAX value from the array.
whats the best way to find second and third values?



$a = array("red", "green", "blue", "blue", "yellow", "yellow", "yellow");
$r = array_count_values($a);
$k = array_search(max($r), $r);
echo "top $k";

djr33
05-05-2012, 04:12 AM
Use sort() to order the array. Then pick $a[1] for second, and $a[2] for third. (And $a[0] for first if you want, replacing what you have now.) In your case, you'd need to use it for the $r array, but that would work.
Right? I think that works for you. Let me know if it doesn't.

ggalan
05-05-2012, 04:34 AM
$r array will give it order but

sort($r);
//$one = $r[0];
$two = $r[1];
$three = $r[2];
echo "most frequent value is $k
SECOND $two
third $three";
gives numeric values when echo'd:

most frequent value is 1 SECOND 1 third 2

traq
05-05-2012, 04:38 AM
the only problem there is that sort() overwrites the array keys...

This works, and unfortunately I don't think there's a quicker way...
$a = array("red", "green", "blue", "blue", "yellow", "yellow", "yellow");
$b = array_count_values( $a );
arsort( $b );
$c = array_flip( $b );

$first = array_shift( $c );
$second = array_shift( $c );
$third = array_shift( $c );

print "Most frequent value is $first<br>Second is $second<br>Third is $third";
// Outputs:
/*
Most frequent value is yellow
Second is blue
Third is red
*/
note, however, how the "tie" between green and red is handled :(
that would be even more complex to deal with...