Skip to content

Instantly share code, notes, and snippets.

@WenLiangTseng
Created February 10, 2014 15:07
Show Gist options
  • Save WenLiangTseng/8917532 to your computer and use it in GitHub Desktop.
Save WenLiangTseng/8917532 to your computer and use it in GitHub Desktop.
PHP Count by sub-array Key & Value
<?php
//Source http://stackoverflow.com/questions/13329621/count-sub-elements-of-an-array-in-php
function array_count ($array, $key, $value = NULL) {
// count($array[*][$key])
$c = 0;
if (is_null($value)) {
foreach ($array as $i=>$subarray) {
$c += ($subarray[$key]!='');
}
} else {
foreach ($array as $i=>$subarray) {
$c += ($subarray[$key]==$value);
}
}
return $c;
}
Example:
// assume $foo is an array of 100 arrays,
// of which 20 sub-arrays have a blank 'description',
// and 35 have 'is_active' set to 'Y' and 65 set to 'N'
echo array_count ($foo, 'description'); // ... 80 non-blanks
echo array_count ($foo, 'is_active'); // ... 100 non-blanks
echo array_count ($foo, 'is_active', 'Y'); // ... 35 matches
echo array_count ($foo, 'description', ''); // ... 20 is-blanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment