Open In App

PHP | Second most frequent element in an array

Improve
Improve
Like Article
Like
Save
Share
Report

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);
      
    // new array containing frequency of values of $arr
    $arr_freq = array_count_values($arr);    
      
     // arranging the new $arr_freq in decreasing order 
     // of occurrences
     arsort($arr_freq);
       
     // $new_arr containing the keys of sorted array
     $new_arr = array_keys($arr_freq);
       
     // Second most frequent element
     echo "Second most frequent element is:"." ".$new_arr[1];
?>


Output:

Second most frequent element is: 4

Example 2:




<?php
      
      
    $arr = array("Geeks", "for", "Geeks");
      
    // new array containing frequency of values of $arr
    $arr_freq = array_count_values($arr);
         
    // arranging the new $arr_freq in decreasing 
    // order of occurrences
    arsort($arr_freq);
       
    // $new_arr containing the keys of sorted array
    $new_arr = array_keys($arr_freq);
       
    // Second most frequent element
    echo "Second most frequent string is:"." ".$new_arr[1];
?>


Output:

Second most frequent string is: for


Last Updated : 11 Apr, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads