Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Dec 2006
    Posts
    417
    Thanks
    168
    Thanked 1 Time in 1 Post

    How do you count link elements in an array?

    I have created an array. I would like to count the frequencies of each element in the array. So if "news" appears 5 times in my array I would have a count of 5.

    Sample array:

    print_r($tagArray);

    Array ( [0] => blog [1] => social [2] => Bluesnews [3] => games [4] => games [5] => social [6] => news [7] => news [8] => Fox [9] => webgame [10] => ajax )

    how does one count the frequency for each element in the array?

    (I am trying to make a tag could -- the more frequent the tag appears the larger the font)

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts

  • #3
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    PHP Code:
    $tagArray = array('blog''social''Bluesnews''games''games''social''news''news''Fox''webgame''ajax');
    $count = array();
    foreach(
    $tagArray as $tag)
        
    $count[$tag]++;

    arsort($count);    
    print_r($count); 
    Output:
    Code:
    Array ( [news] => 2 [games] => 2 [social] => 2 [ajax] => 1 [webgame] => 1 [Fox] => 1 [Bluesnews] => 1 [blog] => 1 )

  • #4
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Quote Originally Posted by Inigoesdr View Post
    PHP Code:
    $tagArray = array('blog''social''Bluesnews''games''games''social''news''news''Fox''webgame''ajax');
    $count = array();
    foreach(
    $tagArray as $tag)
        
    $count[$tag]++;

    arsort($count);    
    print_r($count); 
    Output:
    Code:
    Array ( [news] => 2 [games] => 2 [social] => 2 [ajax] => 1 [webgame] => 1 [Fox] => 1 [Bluesnews] => 1 [blog] => 1 )
    Much simpler to use array_count_values()...

  • #5
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    Must have been sleep typing again. Missed that first post too..


  •  

    Posting Permissions

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