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
- Python | Program to crawl a web page and get most frequent words
- How to get the first element of an array in PHP?
- Removing Array Element and Re-Indexing in PHP
- PHP | Deleting an element from array using array_diff()
- How to delete an array element based on key in PHP?
- How to remove an array element in a foreach loop?
- Sort a multidimensional array by date element in PHP
- PHP program to find missing element(s) from an array
- PHP | Program to delete an element from array using unset() function
- How to remove parent element except its child element using jQuery ?
- jQuery | Move an element into another element
- CSS | element > element Selector
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.