hello,
i've been wondering how to find the most frequently occurring value in an array? the array is going to be consist of either numbers or strings or mixed.
Printable View
hello,
i've been wondering how to find the most frequently occurring value in an array? the array is going to be consist of either numbers or strings or mixed.
not sure if this would be the most efficient way, but I wrote a quick function to do what you want. it will return the most recurring value and how many times it recurred in the array. this will not work for multidimensional arrays but it might be easy to make it do so.
and you could use it like so:PHP Code:function array_mostrecurring($array){
//check if we have an array
if(!is_array($array)) return false;
$c = array(); //counting array
$return['value'] = ""; //highest value (str)
$return['count'] = 0; //highest value (int)
foreach($array as $value){
$c[$value]++;
if($c[$value] > $return['count']){
$return['count'] = $c[$value];
$return['value'] = $value;
}
}
return $return;
}
in this example, there are six values of 1 and six values of 9, but because the 9s were all found first -- setting the highest recurring value at 6 -- it will returns 9 as being the most recurring value. it will print the following:PHP Code:<pre>
<?php
$test_array = array(1, 1, 1, 3, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 1, 1, 1);
print_r(array_mostrecurring($test_array));
?>
</pre>
which means you can use it like so:Code:Array
(
[value] => 9
[count] => 6
)
let me know if that works for you.PHP Code:<?php
$my_array = array_mostrecurring($other_array);
echo "The highest recurring value in $other_array is " . $my_array['value'] . "! It recurred " . $my_array['count'] . " times.";
?>
edit: oh, and this will work fine with both strings and integers. integers were just easier to use for an example.
Here's a shorter alternative.
PHP Code:function array_mode($v)
{
$z = array_count_values($v);
arsort($z);
$k = array_keys($z);
return $k[0];
}
thank you both very much. i like penagate's short function. could please explain the algorithm to me?
array_count_values counts the frequency of every unique value in the input array and produces an output array composed of the values as keys and their frequencies as values. arsort sorts the array by value (frequency, in this case) in reverse, while preserving key/value associativity; this gives us the modal value as the first element of the array. array_keys produces an array whose values are the keys of the input array; this is so that we can return the value rather than its frequency.