Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_count_values

array_count_values

Counts all the values of an array (PHP 4, PHP 5)
array array_count_values ( array input )

Example 236. array_count_values() example

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

The above example will output:

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

Related Examples ( Source code ) » array_count_values



Code Examples / Notes » array_count_values

manuzhai

You might use serialize() to serialize your objects before analyzing their frequency. :)

tschneider

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


jon

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.


meyermagic

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;
}
?>


blauauge

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]
";
     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.


alwaysdrunk

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
?>


digleu

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;
}
?>


mr.a

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]++;
 }
}


rabies dot dostojevski

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.


byron

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


programmer

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


pmarciatigeneticsimediharvardiedu

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!".


coda

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.


meyermagic

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);
}
?>


majerm

<?
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
)


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker