PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_diff_assoc> <array_combine
Last updated: Fri, 26 Dec 2008

view this page in

array_count_values

(PHP 4, PHP 5)

array_count_valuesCompte le nombre de valeurs d'un tableau

Description

array array_count_values ( array $input )

Retourne un tableau contenant les valeurs du tableau input comme clés et leur fréquence comme valeurs.

Liste de paramètres

input

Le tableau de valeurs à compter

Valeurs de retour

Retourne un tableau associatif de valeurs ayant dont les clés correspondent à input et leurs nombres comme valeurs.

Erreurs / Exceptions

Lance une alerte de niveau E_WARNING pour chaque élément qui n'est pas une chaîne de caractères ou un entier.

Exemples

Exemple #1 Exemple avec array_count_values()

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

L'exemple ci-dessus va afficher :

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



array_diff_assoc> <array_combine
Last updated: Fri, 26 Dec 2008
 
add a note add a note User Contributed Notes
array_count_values
psbauman
18-Dec-2008 10:48
This doesn't seem to be documented, but it appears that array_count_values will write its key values *back* to corresponding values in the argument array.

For example, say I have an array $id_numbers, consisting of 7 digits which contain leading zeros (so number 1 would be 0000001 and so on). Most probably already know that array_count_values will (lamely, IMO) strip the leading zeros and return the key as a number.

So if
<?php
$id_numbers
[0] = 0056789;
$id_numbers[1] = 0012345;
$id_numbers[2] = 0012345;

// then
$id_counts = array_count_values($id_numbers); // will yield

$id_counts[56789] = 1;
$id_counts[12345] = 2;

/* That's not the weird part yet.  If you dump $id_numbers you get an interesting result: */

$id_numbers[0] = 56789;
$id_numbers[1] = 12345;
$id_numbers[2] = 12345;
?>

Obviously quite nasty, if you aren't careful.

The way to prevent this is to encapsulate the argument array in the array_values() function:

$id_counts = array_count_values(array_values($id_numbers))

You'll still have the nagging problem that your $id_counts keys are still technically incorrect, but depending on your program or incoming data, a sprintf() should rectify the stripping of zeros (i.e. you basically have to make the array_count_values result a "temporary" array, then loop through that, restore the zeros and populate a new "real" array with correct keys)
bluej100@gmail
25-Mar-2008 10:37
byron at byronrode dot co dot za, here are some benchmarks.

<?php
$haystack
= Array();
for (
$i = 0; $i < 1000000; $i++) {
 
$haystack[] = rand(1, 2000);
}

$needle = rand(1, 2000);

echo
"__array_count_values()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$counts = array_count_values($haystack);
$mem = memory_get_usage()-$startmem;
echo
'Count:'.$counts[$needle]."\n";
echo
'Time:'.(microtime(true) - $start)."\n";
echo
'Memory:'.$mem."\n\n";

echo
"__array_keys()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$keys = array_keys($haystack, $needle);
$mem = memory_get_usage()-$startmem;
echo
'Count:'.count($keys)."\n";
echo
'Time:'.(microtime(true) - $start)."\n";
echo
'Memory:'.$mem."\n\n";

echo
'__$needle_array[]__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
for(
$i = 0; $i < $x; $i++){
  if(
$haystack[$i] == $needle){
   
$needle_array[] = $haystack[$i];
  }
}
$mem = memory_get_usage()-$startmem;
$number_of_instances = count($needle_array);
echo
'Count:'.$number_of_instances."\n";
echo
'Time:'.(microtime(true) - $start)."\n";
echo
'Memory:'.$mem."\n\n";

echo
'__$number_of_instances++__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
$number_of_instances = 0;
for(
$i = 0; $i < $x; $i++){
  if(
$haystack[$i] == $needle){
   
$number_of_instances++;
  }
}
$mem = memory_get_usage()-$startmem;
echo
'Count:'.$number_of_instances."\n";
echo
'Time:'.(microtime(true) - $start)."\n";
echo
'Memory:'.$mem."\n\n";
?>

[www]mytemp$ php array_count_test.php
__array_count_values()__
Count:515
Time:0.0607650279999
Memory:120328

__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016

__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792

__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0

However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:

__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328

__array_keys()__
Count:499
Time:0.36399102211
Memory:30072

__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104

__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0

Results are similar for string->string haystacks with foreach traversal.
Hayley Watson
13-Mar-2008 08:37
Yet Another case-insensitive version of array_count_values()

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

$ar = array_count_values(array_map('strtolower', $ar));
?>
byron at byronrode dot co dot za
26-Jun-2007 02: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 04: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 10: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 03: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 11: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 02: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 09: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 11: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 06: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 08: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 11: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 02: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 03:45
You might use serialize() to serialize your objects before analyzing their frequency. :)
jon at fuck dot org
14-Aug-2002 11: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 04: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...

array_diff_assoc> <array_combine
Last updated: Fri, 26 Dec 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites