Max value in array

Discussion in 'PHP' started by Mr Happy, Aug 14, 2010.

  1. #1
    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
     
    Mr Happy, Aug 14, 2010 IP
  2. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #2
    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:
     
    Kaizoku, Aug 14, 2010 IP
  3. jpratama

    jpratama Member

    Messages:
    31
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #3
    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.
     
    jpratama, Aug 14, 2010 IP
  4. Mr Happy

    Mr Happy Greenhorn

    Messages:
    48
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    20
    #4
    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.
     
    Mr Happy, Aug 14, 2010 IP
  5. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #5
    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.
     
    Kaizoku, Aug 14, 2010 IP