Counting occurrence of specific value in an Array with PHP [duplicate]
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
Not native, but come on, it's simple enough. ;-)
Alternatively:
echo count(array_filter($array, function ($n) { return $n == 6; }));
Or:
echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);
Or:
echo count(array_keys($array, 6));
This solution may be near to your requirement
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
print_r(array_count_values($array));
Result:
Array
( [1] => 1 ,[2] => 1 , [3] => 3, [4] => 2,[5] =>1, [6] => 4, [7] => 1 )
for details.
As of PHP 5.4.0 you can use function array dereferencing for the index [6]
of the array resulting from array_count_values()
:
$instances = array_count_values($array)[6];
So to check and assign 0
if not found:
$instances = array_count_values($array)[6] ?? 0;
Assume we have the following array:
$stockonhand = array( "large green", "small blue", "xlarge brown", "large green", "medieum yellow", "xlarge brown", "large green");
1) Copy and paste this function once on top your page.
function arraycount($array, $value){
$counter = 0;
foreach($array as $thisvalue) /*go through every value in the array*/
{
if($thisvalue === $value){ /*if this one value of the array is equal to the value we are checking*/
$counter++; /*increase the count by 1*/
}
}
return $counter;
}
2) All what you need to do next is to apply the function every time you want to count any particular value in any array. For example:
echo arraycount($stockonhand, "large green"); /*will return 3*/
echo arraycount($stockonhand, "xlarge brown"); /*will return 2*/