Given an array we have to find the second most frequent element present in it.
Examples:
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:
Example 1:
<?php
$arr = array (2, 2, 3, 4, 4, 4, 8, 8, 6, 6, 9, 9, 9, 9);
$arr_freq = array_count_values ( $arr );
arsort( $arr_freq );
$new_arr = array_keys ( $arr_freq );
echo "Second most frequent element is:" . " " . $new_arr [1];
?>
|
Output:
Second most frequent element is: 4
Example 2:
<?php
$arr = array ( "Geeks" , "for" , "Geeks" );
$arr_freq = array_count_values ( $arr );
arsort( $arr_freq );
$new_arr = array_keys ( $arr_freq );
echo "Second most frequent string is:" . " " . $new_arr [1];
?>
|
Output:
Second most frequent string is: for
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Apr, 2018
Like Article
Save Article