Skip to content

Instantly share code, notes, and snippets.

@mikestratton
Created May 10, 2015 04:52
Show Gist options
  • Save mikestratton/52275cde8eb5ab61a0d9 to your computer and use it in GitHub Desktop.
Save mikestratton/52275cde8eb5ab61a0d9 to your computer and use it in GitHub Desktop.
Program that finds the most frequent element in an array. (Uses methods: array_count_values, arsort, array_keys)
<?php
//Program that finds the most frequent element in an array.
$data=Array();
echo "Enter numbers:";
for($i=0;$i<6;$i++)
{
$data[$i]=trim(fgets(STDIN));;
}
// Using methods: array_count_values, arsort, array_keys
$count=array_count_values($data);//Counts the values in the array, returns associative array
arsort($count);//Sort high to low
$freqElem=array_keys($count);//Split the array so we can find the most occurring key
echo "The most occurring value is ".$freqElem[0][1]." with ".$freqElem[0][0]." occurrences.";
exit;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment