I have an array like below. How do I get it to return the max name? $array = array('Apple','Apple','Grape','Orange','Orange','Lemon','Pear','Apple'); PHP: In the above example how do I get it to return 'Apple' I can get the maximum count which is 4 with: $answer = max(array_count_values($array)); PHP: But I need the name too. Any help would be greatly appreciated. Thanks in advance
Try this. $answer = array_count_values($array); asort($answer); // sort $new_answer = array_pop($answer); // gets last value PHP: edit: I think that just gives frequency. something new. abit messy, hope you can find a better way. $answer = array_count_values($array); arsort($answer); // sort reverse // gets first key foreach ($answer as $key => $value) { $new_answer = $key; break; } echo $new_answer; PHP:
A bit tricky several ways to accomplish this. You might also want to try $array = array('Apple','Apple','Grape','Orange','Orange','Lemon','Pear','Apple'); $a = array_count_values($array); $max_value = max($a); // You just have to add this additional line to extract Apple as the max key $max_key = array_search($max, $a)); PHP: Hope that helps.
Thanks so much for the fast replies. Both worked perfectly. I'm going with jpratama as it's slightly faster (I think) not having to go through a foreach loop. For anyone else who stumbles across this their's a minor error fixed. $a = array_count_values($array); $max_value = max($a); // You just have to add this additional line to extract Apple as the max key $max_key = array_search($max_value, $a); PHP: Thanks again for your help. I appreciate it.
Actually, it doesn't go through the entire loop, only once, notice the break. The array_search is a loop itself, probably implemented in it's C function counterpart. Have to benchmark to see which is faster, but the difference is trivial, which ever works for you.