Jump to content

Count array


geckoo

Recommended Posts

I have the following array:

 

Array ( [item0] => Array ( [0] => name1
                                         [1] => name2 
                                         [2] => name3 
                                         [3] => name4 
                                         [4] => name5 )

etc...

 

Is it possible to count the number of times a name exists in the compleet array?

 

Thanx in advance!

Link to comment
Share on other sites

Thanx for the fast reply but i was maybe the following example is better:

 

 

Array ( [item0] => Array ( [0] => peter
                                         [1] => michael 
                                         [2] => kirsten 
                                         [3] => henry 
                                         [4] => james )
            [item1] => Array ( [0] => henry
                                         [1] => james 
                                         [2] => peter 
                                         [3] => brad 
                                         [4] => ford )

 

So what I need to know is how many times for instance name "james" is represented in the entire array. 

 

james = 2

peter = 2

henry = 1

etc...

 

Link to comment
Share on other sites

I don't think array_count_values() will work, as it's a multi-dimensional array. You could maybe do this:

 

$total_count = array();
foreach($array as $values)
{
  $new_count = array_count_values($values);
  foreach($new_count as $key=>$count)
  {
    if(isset($total_count[$key])
    {
      $total_count[$key] += $count;
    }
    else
    {
      $total_count[$key] = $count;
    }
  }
}

$total_count will be an array of names with the count for each name.

Note: untested. may also not need the if/else statement (test it to find out). This may work:

$total_count = array();
foreach($array as $values)
{
  $new_count = array_count_values($values);
  foreach($new_count as $key=>$count)
  {
    $total_count[$key] += $count;
  }
}

I'm just not sure if the += sign works if the original array key isn't set. Maybe try the second block of code before the first.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.