array_count_values

(PHP 4, PHP 5)

array_count_values -- 统计数组中所有的值出现的次数

说明

array array_count_values ( array input )

array_count_values() 返回一个数组,该数组用 input 数组中的值作为键名,该值在 input 数组中出现的次数作为值。

例 1. array_count_values() 例子

<?php
$array
= array(1, "hello", 1, "world", "hello");
print_r(array_count_values ($array));
?>

上例将输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

参见 count()array_unique()array_values()count_chars()


add a note add a note User Contributed Notes
byron at byronrode dot co dot za
26-Jun-2007 12:19
I am building a script for a quiz, and could not find any answers to count the number of times a value was repeated in an array, and came up with the following function.

<?php

// Answers Array
$array = array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

// Start Count Function
function count_repeat_values($needle, $haystack){
  
  
$x = count($haystack);
  
   for(
$i = 0; $i < $x; $i++){
      
       if(
$haystack[$i] == $needle){
          
$needle_array[] = $haystack[$i];
       }
   }
  
  
$number_of_instances = count($needle_array);
  
   return
$number_of_instances;
}

echo
count_repeat_values('a', $array);

// will return the value 5
?>

But after writing the function, I happened to stroll upon array_count_values() which I had completely forgotten about.

I know that i could get the value by doing this:

<?php

$array
= array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

$answer = array_count_values($array);
echo
$answer['a']

?>

Would be interesting to see which version works quicker...
majerm at gmail dot com
18-Jun-2007 02:50
<?
function array_icount_values($array) {
  
$ret_array = array();
   foreach(
$array as $value) $ret_array[strtolower($value)]++;
   return
$ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar = array_icount_values($ar);
?>

this prints:

Array
(
   [j. karjalainen] => 4
   [60] => 2
   [fastway] => 4
   [yup] => 1
)
rabies dot dostojevski at gmail dot com
21-Feb-2007 09:40
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

<pre><?php
function array_icount_values($array) {
  
$ret_array = array();
   foreach(
$array as $value) {
       foreach(
$ret_array as $key2 => $value2) {
           if(
strtolower($key2) == strtolower($value)) {
              
$ret_array[$key2]++;
               continue
2;
           }
       }
      
$ret_array[$value] = 1;
   }
   return
$ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // Normal matching
$ar = array_icount_values($ar); // Case-insensitive matching
print_r($ar2);
print_r($ar);
?></pre>

This prints:

Array
(
   [J. Karjalainen] => 3
   [60] => 2
   [j. karjalainen] => 1
   [Fastway] => 2
   [FASTWAY] => 1
   [fastway] => 1
   [YUP] => 1
)
Array
(
   [J. Karjalainen] => 4
   [60] => 2
   [Fastway] => 4
   [YUP] => 1
)

I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
meyermagic at gmail dot com
17-Jan-2007 02:43
Scratch that, I did something stupid. Here is a better function.

<?php
  
function array_enumerate_keys($array)
   {
      
$index = 0;
      
$enumerated = array();
      
$values = array_values($array);
      
$keys = array_keys($array);
       for(
$index = 0; $index < count($array); $index++)
       {
          
$iteration;
           for(
$iteration = 0; $iteration < $values[$index]; $iteration++)
           {
              
$enumerated = array_merge($enumerated, array($keys[$index]));
           }
       }
      
       return
$enumerated;
   }
?>
meyermagic at gmail dot com
16-Jan-2007 10:58
A possible inverse function for array_count_values

<?php
  
function array_enumerate_keys($array)
   {
      
$index;
      
$enumerated;
      
$values = array_values($array);
      
$keys = array_keys($array);
       for(
$index = 0; $index < count($array); $index++)
       {
          
$iteration;
           for(
$iteration = 0; $iteration < $values[$index]; $iteration++)
           {
              
$enumerated .= $keys[$index] . ',';
           }
       }
      
       return
explode(',', $enumerated);
   }
?>
coda at bobandgeorge dot com
14-Oct-2005 12:52
alwaysdrunk's comment only works if you can trust the client web browser. Using this function doesn't validate that every necessary field exists -- only that every field that was submitted has a value in it. Thus if an attacker wished to force a null value into one of the fields, he could (rather easily) construct a modified form without the field and submit THAT.

Besides, you really ought to be validating each field anyway if you're taking user input.
alwaysdrunk at gmail com
12-May-2005 07:14
if you have too many values in $_POST,$_GET array that needs to be controlled with isset() in oreder to understand the form is filled completely and have no empty text boxes.
you can try this,it saves time.

<?
$n
= array_count_values($_POST);
if (!isset(
$n[''])) {
echo
"The form is filled completely";
}
else
{ die(
"Please fill the form comlpetely"); }

//tested in php 5
?>
[Mr.A]
06-Mar-2005 10:59
I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :

foreach ($array as $a) {
  foreach ($a as $b) {
   $count_values[$b]++;
  }
}
blauauge at figh7club dot com
04-Sep-2003 04:12
my solution for count  on multidimentional arrays.

<?php
 
for($i = 0; $i < count($array); $i++) {
    
$detail = explode("|", $array[$i]);
     echo
"$i - $detail[0] - $detail[1]<br><br>";
     if(
$detail[1] == '1') { $wieoft1 = $wieoft1 +=1; }
     if(
$detail[1] == '2') { $wieoft2 = $wieoft2 +=1; }
     if(
$detail[1] == '3') { $wieoft3 = $wieoft3 +=1; }
  }
  echo
". $wieoft1 : $wieoft2 : $wieoft3";
?>

looks not pretty fine yet works great for me.
make it bigger for your own.
programmer at bardware dot de
19-Aug-2003 06:24
array_count_values returns the number of keys if empty(value). I expected array_count_values to return 0 for empty values.

Array looks like:
Array
       (
           [459] =>
           [543] =>
           [8959] =>
           [11273] =>
       )

array_count_values returns:
Array
(
   [] => 4
)

count(array_count_values(array)) does thus not report there are no values (other than empty) in the array.

I therefore check:
$arrFoo=array_count_values($arrBar);
if(isset($arrFoo[""]) $allempty=count($arrBar)==$arrFoo[""];
if(!$allempty)
//process the array
else
//no need to work on the array
digleu at codeway dot de
28-May-2003 09:58
I fount a solution for the count of array elements in the sense of array_count_values, but i was not able to use the function array_count_values itself because it does not say me if arrays exists in the given array, so i had to use a foreach loop and a little bit of recursivity ;)

<?php
function array_count_values_multidim($a,$out=false) {
  if (
$out===false) $out=array();
  if (
is_array($a)) {
   foreach(
$a as $e)
    
$out=array_count_values_multidim($e,$out);
  }
  else {
   if (
array_key_exists($a,$out))
    
$out[$a]++;
   else
    
$out[$a]=1;
  }
  return
$out;
}
?>
pmarcIatIgeneticsImedIharvardIedu
30-Jan-2003 01:42
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values ($score)" return the error message "Warning: Can only count STRING and INTEGER values!".
manuzhai (AT) php (DOT) net
16-Nov-2002 02:45
You might use serialize() to serialize your objects before analyzing their frequency. :)
jon at fuck dot org
14-Aug-2002 09:31
suggested plan of attack:

<pre>
<?
class MyObject {
   function
MyObject($t = 'none')
   {
    
$this->$myTag = $t;
   }
}

$myArray = array();

for (
$i = 1 ; $i < 11 ; $i++)
{
  
$myobj = new MyObject( str_pad('n', $i, 'x') );
  
$myArray[ $myobj->$myTag ] = $myobj;
}

print_r( array_count_values(array_keys($myArray)) );
?>

to sum up:
assuming each instance of an object you create has some sort of tag, e.g.,

$this->$myTag=get_class($this)

..you should be set. objects dont have value to compare the way strings and integers do, so, $myTag's value is arbitrary.
tschneider at formel4 dot de
12-Jun-2002 02:09
This does not works with objects. If you have an array filled with objects, you can not count them.

Example:

<?php
$myArray
= array();
for (
$i = 0 ; $i < 10 ; $i++)
{
  
$myObject = new MyObject();
  
$myArray[$i] = $myObject;
}

echo (
array_count_values($myArray));
?>

This gives you:
Warning: Can only count STRING and INTEGER values...

Found no solution for this yet...