PHP Velho Oeste 2024

array_count_values

(PHP 4, PHP 5, PHP 7)

array_count_values배열 값의 수를 셉니다

설명

array array_count_values ( array $input )

array_count_values()input 배열값을 키로 사용하고 input 배열의 각 값의 빈도수를 값으로 갖는 배열을 반환한다.

인수

input

값의 수를 셀 배열

반환값

input에서 값을 키로 사용하고, 그 수를 값으로 사용하는 연관 배열을 반환합니다.

오류/예외

string이나 integer가 아닌 모든 원소에 대해서 E_WARNING이 발생합니다.

예제

Example #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 8 notes

up
24
sergolucky96 at gmail dot com
6 years ago
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
?>
up
5
szczepan.krolgmail.c0m
14 years ago
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
)
*/
?>
up
4
rabies dot dostojevski at gmail dot com
17 years ago
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.
up
-2
pmarcIatIgeneticsImedIharvardIedu
21 years ago
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!".
up
-3
anvil_sa at NOSPAMNO dot hotmail dot com
3 years ago
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

?>
up
-4
Dominic Vonk
10 years ago
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;
}
?>
up
-1
Rmr
7 months ago
If you have a multidimensional array with unknown dimensions, you cannot use this function, use instead:

<?php
function array_count_recursive(array $arr): array {
   
$occurrences = [] ;
   
array_walk_recursive( $arr, function($value, $key) use (&$occurrences) {
       @
$occurrences[$value]++;
      
// @ to surpress warnings "Undefined array key". In php8 you can also use
       // $occurrences[$value] = ($occurrences[$value] ?? 0) + 1
   
});
    return
$occurrences;
}   
?>
up
-1
tyler at tloc dot com
1 year ago
A cleaner way to use array_count_values() to find boolean counts.

<?php

$list
= [
  [
'id' => 1, 'result' => true],
  [
'id' => 2, 'result' => true],
  [
'id' => 3, 'result' => false],
];
$result = true;

echo
array_count_values(array_map('intval', array_column($list, 'result')))[(int)$result];
// outputs: 2
?>
To Top