How can I count the number of element inside an array with value equals a constant? example,
$myArray = array(\"Kyle\",\"Ben\",\"Sue\",\"Phil\",\"Ben\",\"Mar
Use array_count_values()
function . Check this link http://php.net/manual/en/function.array-count-values.php
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
define( 'SEARCH_STRING', 'Ben' );
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));
echo $count, "\n";
Output:
3
array_count_values
only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:
function arrayCountValues($arr) {
$vals = [];
foreach ($arr as $val) { array_push($vals,strval($val)); }
$cnts = array_count_values($vals);
arsort($cnts);
return $cnts;
}
Note that I return $cnts
with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.
I tested a version which looped, creating an array of counts rather than using array_count_values
, and this turned out to be more efficient (by maybe 8-10%)!