0

So I have an array, that goes a bit like:

$concat=array("DARK HORSE,KATY PERRY", "DARK HORSE,KATY PERRY", "WHEN IT RAINS,PARAMORE", "LITHIUM,NIRVANA")
//$concat = song and artist together separated by a comma

And I need to output the value that occurs the most, so in the array above I would need to output the string = "DARK HORSE,KATY PERRY"

thank you :)

3 Answers3

0
echo key(array_count_values($concat));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

You can use array_count_values, and array_keys to output the result:

$concat=array("DARK HORSE,KATY PERRY", "DARK HORSE,KATY PERRY", "WHEN IT RAINS,PARAMORE", "LITHIUM,NIRVANA");
//counts frequencies
$count_array = array_count_values($concat);

//gets the keys instead of the values
$count_keys = array_keys($count_array);

//echoes only the first key
echo current($count_keys);

//Or print all values and keys
print_r($count_array);
larsAnders
  • 3,813
  • 1
  • 15
  • 19
0

You can use array_count_values to get an array with the instance as key and the frequency as the value. Then you need to sort the array from high to low maintaining the index (arsort) this is important.

So:

//your array
$concat=array("DARK HORSE,KATY PERRY", "DARK HORSE,KATY PERRY", "WHEN IT RAINS,PARAMORE", "LITHIUM,NIRVANA")

//get all the frequencies
$frequencies = array_count_values($concat);

//make sure to sort it since array_count_values doesn't return a sorted array
arsort($frequencies);

//reset the array because you can't trust keys to get the first element by itself
reset($frequencies);

//get the first key
echo key($frequencies);
Chris
  • 1,068
  • 2
  • 14
  • 30