Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting occurrence of specific value in an Array with PHP [duplicate]

Tags:

arrays

php

I am trying to find a native PHP function that will allow me to count the number of occurrences of a particular value in an array. I am familiar with the array_count_values() function, but that returns the count of all values in an array. Is there a function that allows you to pass the value and just return the instance count for that particular value? For example:

$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);  $instances = some_native_function(6, $array);  //$instances will be equal to 4 

I know how to create my own function, but why re-invent the wheel?

like image 223
Javit Avatar asked May 10 '11 04:05

Javit


People also ask

How do I count occurrence of duplicate items in array?

To count the duplicates in an array:Copied! const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = {}; arr. forEach(element => { count[element] = (count[element] || 0) + 1; }); // 👇️ {one: 3, two: 2, three: 1} console.

How do you count occurrences of each element in an array in PHP?

array_count_values() function in PHP 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.

How can I get only duplicate values from an array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


2 Answers

function array_count_values_of($value, $array) {     $counts = array_count_values($array);     return $counts[$value]; } 

Not native, but come on, it's simple enough. ;-)

Alternatively:

echo count(array_filter($array, function ($n) { return $n == 6; })); 

Or:

echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0); 

Or:

echo count(array_keys($array, 6)); 
like image 140
deceze Avatar answered Sep 28 '22 08:09

deceze


This solution may be near to your requirement

$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7); print_r(array_count_values($array));  Result:  Array ( [1] => 1 ,[2] => 1 , [3] => 3, [4] => 2,[5] =>1, [6] => 4, [7] => 1 ) 

for details.

like image 21
Muhammad Zeeshan Avatar answered Sep 28 '22 07:09

Muhammad Zeeshan