- Count occurrences of values in an associative array in php
- Syntax
- Output
- Answer by Kamden Norris
- Answer by Lukas Barrera
- Answer by Bishop Burke
- Answer by Ruben McClure
- Answer by Iris Hogan
- Answer by Harlem Sims
- Using array_count_values() to Count Occurrence of Value in Array in PHP
- array_count_values
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- See Also
- User Contributed Notes 7 notes
- count
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
Count occurrences of values in an associative array in php
The array_count_values() function returns an associative array. The returned array has keys as the array’s values, whereas values as the count of the passed values.,The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array’s values, whereas values as the count of the passed values.,arr − The array for which we want to count the values.,clearstatcache() function in PHP
Syntax
Output
Array ( [Laptop] => 1 Count associative array php => 4 [Mouse] => 2 )
Answer by Kamden Norris
array_column — Return the values from a single column of array. array_count_values — Counts all the values of an array.,Please help me on how to count the occurrences of value in this associative array.,Combination of array_count_values & array_column (PHP 5 >= 5.5.0, PHP 7) should work — ,You can use array_count_value() pre-define php function to get your aim. you can see result here
Combination of array_count_values & array_column (PHP 5 >= 5.5.0, PHP 7) should work —
$counts = array_count_values( array_column($employees, 'position') );
array(3) < [1]=>int(1) [2]=> int(2) [3]=> int(2) >
$final = array_filter($counts, function($a) < return $a >= 2; >);
Answer by Lukas Barrera
Returns an associative array of values from array as keys and their count as value. , array_count_values() returns an array using the values of array as keys and their frequency in array as values. ,array_values() — Return all the values of an array, The array of values to count
Array ( [1] => 2 [hello] => 2 [world] => 1 )
Answer by Bishop Burke
How it works: array_count_values() function returns an associative array with the number of occurrence of each element. If you print the $friends_count, you’ll see the following-,To find the number of occurrence of an array element, follow the steps below-,To show the number of occurrence of an element(ex. Mark), use Mark as key in the associative array that we got in the step 1.,If you use the above array as parameter in the array_count_values() function, it will return an associative array whose keys are the values of the above array and values are the number of occurrence of each element of the above array.
You have an array (see the following array) which has some repeating elements. You want to count the number of occurrence of a specific element(for ex. Mark).
$friends = array("Mark", "Caroline", "Douglas", "Brian", "Mark", "John", "John");
See the complete example below-
How it works:
array_count_values() function returns an associative array with the number of occurrence of each element. If you print the $friends_count, you’ll see the following-
Array( [Mark] => 2 [Caroline] => 1 [Douglas] => 1 [Brian] => 1 [John] => 1 )
Answer by Ruben McClure
$array = ['x', 'y', 'z']; count($array); // output 3 size_of($array); // output 3
Answer by Iris Hogan
PHP array_count_values() function counts the occurrences of all values in an array and returns an associative array formed by the unique value of input array as keys, and the number of their occurrences in the array as values.,The array_count_values() function returns an array formed with unique values as keys, and their number of occurrences as values.,In this PHP Tutorial, we learned how to count occurrences of values in a given array, using PHP Array array_count_values() function.,In this tutorial, we will learn the syntax of array_count_values(), and how to use array_count_values() to count the occurrences of values in the array, covering different scenarios based on array type and arguments.
The syntax of PHP array_count_values() function is
array_count_values ( array $input ) : array
PHP Program
PHP Program
41, 'key2'=>'a', 'key3'=>41, 'key4'=>'a', 'key5'=>'b' ); $result = array_count_values($input); print_r($result) ?>
PHP Program
Answer by Harlem Sims
How to Count Occurrence of Specific Value in Array in PHP,Using array_count_values() to Count Occurrence of Value in Array in PHP,In this tutorial, learn how to count occurrence of value in array using PHP. The short answer is to use the PHP array_count_values() Function of PHP that takes a single argument as an array.,Tutorialdeep » knowhow » PHP Faqs » How to Count Occurrence of Value in Array in PHP
Using array_count_values() to Count Occurrence of Value in Array in PHP
To count the occurrence of value in an array, you can use the array_count_values() function. It takes a single argument that is the array or array variable to pass to the function. The function counts the occurrences of all the elements present in an array in PHP.
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!».
- Array Functions
- 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_is_list
- array_key_exists
- array_key_first
- array_key_last
- 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
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
count
Подсчитывает количество элементов массива или что-то в объекте.
Для объектов, если у вас включена поддержка SPL, вы можете перехватить count() , реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count() , который возвращает значение функции count() .
Пожалуйста, смотрите раздел «Массивы» в этом руководстве для более детального представления о реализации и использовании массивов в PHP.
Список параметров
Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.
count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.
Возвращаемые значения
Возвращает количество элементов в array_or_countable . Если параметр не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если array_or_countable — NULL , то будет возвращён 0.
count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.
Примеры
Пример #1 Пример использования count()
$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
$result = count ( $a );
// $result == 3?php
$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
$result = count ( $b );
// $result == 3$result = count ( null );
// $result == 0$result = count ( false );
// $result == 1
?>Пример #2 Пример рекурсивного использования count()
$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));?php
// рекурсивный count
echo count ( $food , COUNT_RECURSIVE ); // выводит 8// обычный count
echo count ( $food ); // выводит 2Смотрите также
- is_array() — Определяет, является ли переменная массивом
- isset() — Определяет, была ли установлена переменная значением отличным от NULL
- strlen() — Возвращает длину строки