Use the array_count_values function.
$countValues = array_count_values($myArray);
echo $countValues["Ben"];
If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:
function countSame($array) {
$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;
if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);
$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])
} //end of while ($count > 0)
return $storeArray;
} //end of function countSame($array)
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%)!
try the array_count_values() function
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3
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
To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-
<?php
$list = [
['id' => 1, 'userId' => 5],
['id' => 2, 'userId' => 5],
['id' => 3, 'userId' => 6],
];
$userId = 5;
echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
Try the PHP function array_count_values
.
Use array_count_values()
function . Check this link http://php.net/manual/en/function.array-count-values.php
Source: Stackoverflow.com