PHP: How to find the 2nd most common item in an array?
Let's say you have an array with values of people's names. You want to find the 2nd most common name. How would you do this?
First you want to get a count of all values. Luckily PHP has this built in.
- $names = [
- $what_position_we_want = 2;
- $vals = array_count_values($names);
- // var_dump($vals) = ['Bart' => 5, 'Lisa' => 1, 'Amy' => 1, 'Philip' => 3, ...]
So now that we have an array where the keys are the names, and the values are the count of how many times they appear, we just need to sort it and pick the 2nd item.
To pick the 2nd element of the array, we need to use array_keys() so the array is numerically indexed...
- // we want it in reverse (so we can do $vals to get the 2nd item)
- // rsort($vals) would sort it (in reverse), however it assigns new keys (we need to key to know what name it is!)
- // so we have to do arsort()
- // we need to get an array with the values (names) keyed by id, so we can do $keys
- $keys = array_keys($vals);
- echo "The $what_position_we_want most popular name is: " . $keys[$what_position_we_want-1];
The 2 most popular name is: Philip