array count values code example

Example 1: php count array elements with specific key

$cnt = count(array_filter($array,function($element) {
  return $element['your_key']=='foo';
}));

Example 2: php count amount of times a value appears in array

$tmp = array_count_values($uid);
$cnt = $tmp[12];
//Or
$cnt = count(array_filter($uid,function($a) {return $a==12;}));
//In both cases $var will be a number

Example 3: Count elements in an array

//#Source https://bit.ly/2neWfJ2 
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 1));
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 2));
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 3));

Tags:

Misc Example