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 kind of database field type should you (normally) use for foreign keys?

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

What are the predefined variables in PHP?

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

How to prevent Eloquent from adding created_at or updated_at timestamps?

How do you launch the PHP interactive shell?

How to find out what version of Laravel you are using?

How to convert between types in JS?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to order a Laravel hasMany relationship?