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 (
n) { return
n == 6); }, 0);
Or:
echo count(array_keys($array, 6));
Answer from deceze on Stack Overflowfunction 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 (
n) { return
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.
http://php.net/array_count_values
Did you attempt to research this at all?
cv = array_count_values($arr);
echo
key];
That's how you get the count for ONE value.
array_count_values($array)
reference http://php.net/manual/en/function.array-count-values.php
same question at here
In PHP7 you can use the NULL coalescing operator to simplify this code:
$a=['a','b','a','c','a','d'];
$output=[];
foreach ($a as $v) {
$output[$v] = ($output[$v] ?? 0) + 1;
}
print_r($output);
Output:
Array
(
[a] => 3
[b] => 1
[c] => 1
[d] => 1
)
Demo on 3v4l.org
As mentioned in the comments array_count_values() is the optimal solution in php. But you must write it out aka show your understanding on how to search an array its rather simple as well.
$a=['a','b','a','c','a','d'];
$output=[];
for($i = 0; $i < count($a); $i++){
if(!isset($output[$a[$i]])){
$output[$a[$i]] = 1;
}
else{
$output[$a[$i]] = $output[$a[$i]] + 1;
}
}
var_dump($output);
//output
array(4) {
["a"] => int(3)
["b"] => int(1)
["c"] => int(1)
["d"] => int(1)
}
To count matching occurance of a string in multidimensional array you will need to iterate over each array element and match the string and increment the count. Similiarly @Dor has suggested
$count = 0;
foreach ($array as $item) {
if ($item->type === 'photo') {
$count++;
}
}
If you want achieve same in single dimensional array then It's pretty straightforward. You can use array_count_values PHP array function as explained below.
<?php
$array = array(1, "test", 1, "php", "test");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[test] => 2
[php] => 1
)
$count = 0;
foreach ($array as $item) {
if ($item->type === 'photo') {
$count++;
}
}
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3