Advanced Search

Results 1 to 4 of 4

Thread: frequency in array

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default frequency in array

    i have the following code which gets the MAX value from the array.
    whats the best way to find second and third values?

    Code:
    $a = array("red", "green", "blue", "blue", "yellow", "yellow", "yellow");
    $r = array_count_values($a);
    $k = array_search(max($r), $r);
    echo "top $k";
    Last edited by ggalan; 05-05-2012 at 04:25 AM.

  2. #2
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,156
    Thanks
    262
    Thanked 690 Times in 678 Posts

    Default

    Use sort() to order the array. Then pick $a[1] for second, and $a[2] for third. (And $a[0] for first if you want, replacing what you have now.) In your case, you'd need to use it for the $r array, but that would work.
    Right? I think that works for you. Let me know if it doesn't.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  3. The Following User Says Thank You to djr33 For This Useful Post:

    ggalan (05-05-2012)

  4. #3
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    $r array will give it order but
    Code:
    sort($r);
    //$one = $r[0];
    $two = $r[1];
    $three = $r[2];
    echo "most frequent value is $k
    SECOND $two
    third $three";
    gives numeric values when echo'd:
    Code:
    most frequent value is 1 SECOND 1 third 2

  5. #4
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,632
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    the only problem there is that sort() overwrites the array keys...

    This works, and unfortunately I don't think there's a quicker way...
    PHP Code:
    $a = array("red""green""blue""blue""yellow""yellow""yellow");
    $b array_count_values$a );
    arsort$b );
    $c array_flip$b );

    $first array_shift$c );
    $second array_shift$c );
    $third array_shift$c );

    print 
    "Most frequent value is $first<br>Second is $second<br>Third is $third";
    // Outputs:  
    /*
    Most frequent value is yellow
    Second is blue
    Third is red
    */ 
    note, however, how the "tie" between green and red is handled
    that would be even more complex to deal with...

  6. The Following 2 Users Say Thank You to traq For This Useful Post:

    djr33 (05-05-2012),ggalan (05-05-2012)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •