How to find the 2nd most common item in an array?

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.

  1. $names = [
  2.  
  3.  
  4.     'Bart',
  5.     'Lisa',
  6.     'Amy',
  7.     'Philip',
  8.     'Bart',
  9.     'Fred',
  10.     'Philip',
  11.     'Bart',
  12.     'Fred',
  13.     'Leela',
  14.     'Barney',
  15.     'Philip',
  16.     'Bart',
  17.     'Barney',
  18.     'Ned',
  19.     'Bart'
  20.  
  21.     ];
  22.  
  23. $what_position_we_want = 2;
  24. $vals = array_count_values($names);
  25. // 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...

  1. // we want it in reverse (so we can do $vals[1] to get the 2nd item)
  2. // rsort($vals) would sort it (in reverse), however it assigns new keys (we need to key to know what name it is!)
  3. // so we have to do arsort()
  4. arsort($vals);
  5.  
  6. // we need to get an array with the values (names) keyed by id, so we can do $keys[1]
  7. $keys = array_keys($vals);
  8.  
  9. echo "The $what_position_we_want most popular name is: " . $keys[$what_position_we_want-1];

The 2 most popular name is: Philip
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to find the 2nd most common item in an array?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What is the difference between reference and primitive data types types in Javascript?

Set PHP config Variables (like ini_set) with .htaccess

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to get table column names from a database table in Eloquent?

How to disable file hotlinking in Apache with .htaccess

How to review blog posts (written by other users) before they get published on your WordPress blog?

What are the SPL Iterators in PHP?

How to find the index of a value in an array in JS?

How to Extract Query String (from a URL) Into an Associative Array in PHP

What is the max size, by default, of GET variables?