PHP: array_count_values - Manual

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

search for in the

array_diff_assoc array_combine

Last updated: Sat, 27 Jan 2007

view this page in

# array_count_values

(PHP 4, PHP 5)

array_count_values -- Подсчитать количество всех значений массива

## Описание

array array_count_values ( array input )

Функция array_count_values() возвращает массив, ключами которого являются значения массива `исходный_массив`, а значениями - частота повторения этих значений.

Пример 1. Пример использования array_count_values()

`$array = array (1, "hello", 1, "world", "hello"); print_r(array_count_values ($array));`

Результатом вышеприведенной программы будет:

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

add a note User Contributed Notes
array_count_values
rabies dot dostojevski at gmail dot com
21-Feb-2007 01: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
16-Jan-2007 06: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 02: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 05: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 12: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 02: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
03-Sep-2003 09: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 11: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 02: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
29-Jan-2003 05: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 06:45
`You might use serialize() to serialize your objects before analyzing their frequency. :)`
jon at fuck dot org
14-Aug-2002 02: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 07: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...`
add a note
array_diff_assoc array_combine

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST