Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get the item in an array that has the most duplicates

Tags:

I have an array of strings and I am looking for a way to find the most common string in the array.

$stuff = array('orange','banana', 'apples','orange'); 

I would want to see orange.

like image 865
shaneburgess Avatar asked Dec 05 '10 16:12

shaneburgess


People also ask

How can I get only duplicate values from an array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


2 Answers

$c = array_count_values($stuff);  $val = array_search(max($c), $c); 
like image 133
user187291 Avatar answered Oct 18 '22 06:10

user187291


Use array_count_values and get the key of the item:

<?php $stuff = array('orange','banana', 'apples','orange', 'xxxxxxx');  $result = array_count_values($stuff); asort($result); end($result); $answer = key($result);  echo $answer; ?> 

Output:

orange 
like image 28
shamittomar Avatar answered Oct 18 '22 04:10

shamittomar