PHP: Most frequent value in array
Asked Answered
D

3

20

So I have this JSON Array:

[0] => 238
[1] => 7
[2] => 86
[3] => 79
[4] => 55
[5] => 92
[6] => 55
[7] => 7
[8] => 254
[9] => 9
[10] => 75
[11] => 238
[12] => 89
[13] => 238

I will be having more values in the actual JSON file. But by looking at this I can see that 238 and 55 is being repeated more than any other number. What I want to do is get the top 5 most repeated values in the array and store them in a new PHP array.

Demonstrative answered 3/6, 2015 at 17:24 Comment(1)
What if multiple values share the same number of occurrences, do you want any, all or none of those. E.g. [5,4,2,6,7,3,1] all have one occurrence, which 5 would you choose?Greenbelt
R
63
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
  • array_count_values() gets the count of the number of times each item appears in an array
  • arsort() sorts the array by number of occurrences in reverse order
  • array_keys() gets the actual value which is the array key in the results from array_count_values()
  • array_slice() gives us the first five elements of the results

Demo

$array = [1,2,3,4,238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);

array (
  0 => 238,
  1 => 55,
  2 => 7,
  3 => 4,
  4 => 3,
)
Retraction answered 3/6, 2015 at 17:27 Comment(2)
$this_answer="beauty";Frith
If you want to retrieve then only the most frequent value you can do this $most_popular_value = key($values);Purgatorial
G
10

The key is to use something like array_count_values() to tally up the number of occurrences of each value.

<?php

$array = [238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];

// Get array of (value => count) pairs, sorted by descending count
$counts = array_count_values($array);
arsort($counts);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1, 9 => 1, ...)

// An array with the first (top) 5 counts
$top_with_count = array_slice($counts, 0, 5, true);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1)

// An array with just the values
$top = array_keys($top_with_count);
// array(238, 55, 7, 75, 89)

?>
Greenbelt answered 3/6, 2015 at 18:25 Comment(0)
T
0
function findMajorityElement($nums) {
    $count = 0;
    $candidate = null;

    foreach ($nums as $num) {
        if ($count == 0) {
            $candidate = $num;
        }
        $count += ($num == $candidate) ? 1 : -1;
    }

    return $candidate;
}

// Example Usage
$nums = [2, 2, 1, 1, 1, 2, 2];
$majorityElement = findMajorityElement($nums);
echo $majorityElement . "\n"; // Output: 2
Tenace answered 14/7 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.