find the kth most frequent element in an array in php

To find the kth most frequent element in an array in PHP, we can first calculate the frequency of each element in the array and then sort the array based on the frequency of each element. Once the array is sorted, we can easily find the kth most frequent element by accessing it at index k-1. Here is the code to achieve this:

main.php
function kthMostFrequentElem($arr, $k) {
    // count the frequency of each element in the array
    $freq = array_count_values($arr);
    
    // sort the array based on the frequency of each element
    arsort($freq);
    
    // get the kth most frequent element
    $keys = array_keys($freq);
    return $keys[$k-1];
}

// example usage
$arr = array(1, 2, 3, 2, 2, 3, 4, 4, 4, 4);
$k = 2;
echo kthMostFrequentElem($arr, $k); // output: 3
442 chars
17 lines

In the above code, we first use the array_count_values function to count the frequency of each element in the array. This function returns an associative array where keys are the unique elements in the input array and values are the frequency of these elements in the input array.

Next, we use the arsort function to sort the $freq array in descending order based on the values (i.e., frequency) of the array.

Finally, we use the array_keys function to get an array of keys (i.e., unique elements) in sorted order and then return the kth element of this array (subtracting 1 from k since array indices start from 0).

gistlibby LogSnag