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:

  1. Count the frequency of each element in the array using array_count_values function.
  2. Sort the resulting frequency array in descending order using arsort function.
  3. Get the kth element from the resulting frequency array using array_slice function.

Here's the PHP code for this approach:

main.php
function kthMostCommonElement($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
476 chars
18 lines

gistlibby LogSnag