$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
Answer from Rajat Singhal on Stack Overflow$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
Use array_count _values to get an array with everything counted for you.
Here is just an idea. You could use array_keys($myArray, "") using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array("", "", "other", "", "other");
$length = count(array_keys($myArray, ""));
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)
}
http://php.net/array_count_values
Did you attempt to research this at all?
$key = 5;
$cv = array_count_values($arr);
echo $cv[$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
You're on the right track, but you need to apply array_count_values() to each subarray, not the parent array.
$arr = [
'item1' => [1, 1, 3],
'item2' => [1, 1, 1, 2, 1],
'item3' => [1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
];
$totals = array_map('array_count_values', $arr);
print_r($totals);
Results in
Array
(
[item1] => Array
(
[1] => 2
[3] => 1
)
[item2] => Array
(
[1] => 4
[2] => 1
)
[item3] => Array
(
[1] => 1
[2] => 3
[3] => 6
)
)
So, as @deceze advised - it is:
// applying `array_count_values` to each element of `$array`
print_r(array_map('array_count_values', $array));