PHP | Second most frequent element in an array
Given an array we have to find the second most frequent element present in it.
Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8); Output : Second most frequent element is: 5 Input : array("geeks", "for", "geeks"); Output : Second most frequent element is: for
The above problem can be solved in other languages using loop method, but in PHP we have built in function to perform this task. The functions which are described as follows:
- array_count_values(): This function is used to count the frequency of all the elements and returns the associated array, which contains the values as key and frequency as values.
- arsort(): This function is used to sort the elements in reverse order and maintaining the index associated.
- array_keys(): This function returns an array containing all the keys or subset.
Approach: At first we make a new array containing the frequency of all the elements with values as key and count as values using the array_count_values.
Sorting the new array in reverse order using arsort, then take all the keys of the sorted array using array_keys. Second key will be the second most frequent element of the original array.
Below is the illustration of above approach:
Second most frequent element is: 4
Second most frequent string is: for