Created
February 10, 2014 15:07
-
-
Save WenLiangTseng/8917532 to your computer and use it in GitHub Desktop.
PHP Count by sub-array Key & Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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