SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Evangelist Tecknowjnkie's Avatar
    Join Date
    Nov 2004
    Location
    Mission Viejo
    Posts
    403
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Count Identical String Values in Array

    Stuck on this one -

    PHP Code:
    $arr = array('a','a','a','b','c','c','c' etc...); 
    I need a way to count how many of each same letter instance is present and return an array containing these results.

    PHP Code:
    $newarr = array('a' => '3''b' => '1''c' => '3'); 
    Thank you for replies

  2. #2
    Grumpy Minimalist
    Join Date
    Jul 2006
    Location
    Ontario, Canada
    Posts
    424
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How about this?

    PHP Code:
    $arr = array('a','a','a','b','c','c','c');

    foreach (
    $arr as $value)
    {
        
    $newarr[$value]++;
    }

    var_dump($newarr); 

  3. #3
    SitePoint Member hermawan's Avatar
    Join Date
    Jul 2003
    Location
    Jakarta, Indonesia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    We know there are more simple way to do this. Let's try to have a better understanding with array_walk() and array_key_exists() to solve this problem.

    Here is the function:
    Code:
    function count_unique ($item, $key, $counts)
    {
    	if (array_key_exists ($item, $counts))
    		$counts[$item]++;
    	else
    		$counts[$item] = 1;
    }
    Just reply for more if you don't know how to implement this.
    Hermawan Haryanto
    Red Rock Reef - Asia | hermawan@redrockreef.asia

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  5. #5
    SitePoint Evangelist Tecknowjnkie's Avatar
    Join Date
    Nov 2004
    Location
    Mission Viejo
    Posts
    403
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you all - stereofrog's is King


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
  •