Количество уникальных значений массива php

array_count_values

array_count_values ​​() возвращает массив, используя значения array качестве ключей и их частоту в array качестве значений.

Parameters

Массив значений для подсчета

Return Values

Возвращает ассоциативный массив значений из array как ключей и их количество как значение.

Errors/Exceptions

Выдает E_WARNING для каждого элемента , который не является строкой или внутр.

Examples

Пример # 1 array_count_values () Пример

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

Выводится приведенный выше пример:

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

See Also

  • count () — подсчитывает все элементы в массиве или в объекте Countable
  • array_unique () — Удаляет повторяющиеся значения из массива
  • array_values ​​() — Возвращает все значения массива
  • count_chars () — возвращает информацию о символах, используемых в строке
PHP 8.2

(PHP 5 5.5.0,7,8)array_column Возвращает значения из одиночного ввода array_column()возвращает значения из одиночного ввода,идентифицированного по ключу column_key.

(PHP 4 4.0.1,5,7,8)array_diff Вычисляет разность массивов Сравнивает массив с одним или несколькими другими массивами и возвращает значения,которые не присутствуют в массиве.

(PHP 4 4.3.0,5,7,8)array_diff_assoc Вычисляет разность массивов с дополнительной проверкой индексов Сравнивает массив с массивом и возвращает разность.

Источник

array_count_values

array_count_values() returns an array using the values of array (which must be int s or string s) as keys and their frequency in array as values.

Parameters

The array of values to count

Return Values

Returns an associative array of values from array as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or int .

Examples

Example #1 array_count_values() example

The above example will output:

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

See Also

  • count() — Counts all elements in an array or in a Countable object
  • array_unique() — Removes duplicate values from an array
  • array_values() — Return all the values of an array
  • count_chars() — Return information about characters used in a string

User Contributed Notes 7 notes

Simple way to find number of items with specific values in multidimensional array:

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

Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.

$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
)
*/
?>

I couldn’t find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

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

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.

A cleaner way to use array_count_values() to find boolean counts.

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

The case-insensitive version:

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

Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:

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

echo array_count_values ( array_map (function( $v ) , array_column ( $list , ‘result’ )))[ $result ]
// outputs: 2

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

Оцените статью