array_count_values
(PHP 4, PHP 5)
array_count_values — Подсчитывает количество всех значений массива
Описание
array array_count_values
( array
$input
)
Функция array_count_values() возвращает массив,
ключами которого являются значения массива input
,
а значениями - частота повторения значений input
.
Список параметров
-
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() - Возвращает информацию о символах, входящих в строку
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения, относящиеся к переменным и типам
- Массивы
- array_change_key_case
- array_chunk
- array_column
- 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_replace_recursive
- array_replace
- 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_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
Коментарии
You might use serialize() to serialize your objects before analyzing their frequency. :)
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!".
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]++;
}
}
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.
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.
<?
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
)
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, 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.
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.
<?php
$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array
$res = array_icount_values ($ar1);
print_r($res);
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
/*
Will print:
Array
(
[red] => 3
[green] => 3
[yellow] => 4
[blue] => 2
[brown] => 2
[white] => 1
[black] => 1
)
*/
?>
The case-insensitive version:
<?php
function array_count_values_ci($array) {
$newArray = array();
foreach ($array as $values) {
if (!array_key_exists(strtolower($values), $newArray)) {
$newArray[strtolower($values)] = 0;
}
$newArray[strtolower($values)] += 1;
}
return $newArray;
}
?>
In order to apply array_map with callback checking for localised values like city name, country name, you have to provide some sort of comparison array.
Here's an example of array_count_values for Polish city names. Just switch array_keys / array_values in order to obtain lowercase / uppercase.
$arr = array('Warsaw', 'Warsaw', 'Wrocław', 'Poznań', 'KrakÓw', 'waRsaw', 'Gdańsk', 'poznań', 'WROCŁAW', 'kraków', 'GDAŃSK');
$lowertoupperpolish = array(
'ą' => 'Ą',
'ć' => 'Ć',
'ę' => 'Ę',
'ł' => 'Ł',
'ń' => 'Ń',
'ó' => 'Ó',
'ś' => 'Ś',
'ż' => 'Ż',
'ź' => 'Ź',
);
function lowers($n) {
global $lowertoupperpolish;
return strtolower(str_replace(array_values($lowertoupperpolish), array_keys($lowertoupperpolish), $n));
}
$result = array_count_values(array_map('lowers', $arr));
print_r($result); ...prints:
Array ( [warsaw] => 3 [wrocław] => 2 [poznań] => 2 [kraków] => 2 [gdańsk] => 2 )
$array = array(1, true, 1, true, false,NULL);
var_dump(array_count_values($array));
//Warning: array_count_values(): Can only count STRING and INTEGER values!
Simple example to count the values of a $key in an associative array:
/**
* Associative Array Count Values
*
* Returns an array containing the number of values for a given $key in a given associative $array
*
* @param array $array The associative array to count values for
* @param String $key The key to count values for
* @return array A new array containing the counted values for the key in the original associative array
*/
function assc_array_count_values( $array, $key ) {
foreach( $array as $row ) {
$new_array[] = $row[$key];
}
return array_count_values( $new_array );
}
Simple way to find number of items with specific values in multidimensional array:
<?php
$list = [
['id' => 1, 'userId' => 5],
['id' => 2, 'userId' => 5],
['id' => 3, 'userId' => 6],
];
$userId = 5;
echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
?>
Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:
<?php
$list = [
['id' => 1, 'result' => true],
['id' => 2, 'result' => true],
['id' => 3, 'result' => false],
];
$result = true;
echo array_count_values(array_map(function($v) {return $v?'true':'false';},array_column($list, 'result')))[$result]
// outputs: 2
?>