find the kth most common element in an array in php
To find the kth most common element in an array in PHP, we can follow the below steps:
Count the frequency of each element in the array using array_count_values function.
Sort the resulting frequency array in descending order using arsort function.
Get the kth element from the resulting frequency array using array_slice function.
Here's the PHP code for this approach:
main.php
functionkthMostCommonElement($arr, $k) {
// get the frequency of each element in the array$freq = array_count_values($arr);
// sort frequency array in descending order arsort($freq);
// get the kth element from the frequency array$kthMostCommon = array_slice(array_keys($freq), $k-1, 1, true);
return$kthMostCommon[0];
}
// example usage$arr = array(1, 2, 2, 3, 3, 3);
$k = 2;
echo kthMostCommonElement($arr, $k); // outputs 3