23

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.

1
  • 3
    <nitpick>array( ... );, not { ... }</nitpick> :P Commented Dec 5, 2010 at 16:16

2 Answers 2

41
$c = array_count_values($stuff); 
$val = array_search(max($c), $c);
Sign up to request clarification or add additional context in comments.

Comments

10

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

2 Comments

Nice, bear in mind due to unstable sort it's unpredictable if multiple elements have the same highest frequency in the array.
you can also do array_slice() after doing arsort() if you want the top 5 results for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.