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
https://forums.phpfreaks.com/topic/250608-count-array/
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
https://forums.phpfreaks.com/topic/250608-count-array/#findComment-1285806
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
https://forums.phpfreaks.com/topic/250608-count-array/#findComment-1285828
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.