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

How do you run a PHP script from the command line?

How to output (echo/print) content in PHP

How to replace values in a string, in JS

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

What is Agile software development?

What is the null coalescing operator in PHP7?

How to get the type of a variable in JS?

How to install jpegtran for Linux CentOS

How to add the CSRF (Cross-site request forgery) token in Laravel?

What are the main error types in PHP