PHP - 计算特定数组值

2022-08-30 09:27:05

如何计算数组中值等于常量的元素数?例

$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");

我怎么能直接知道里面有多少个“本”?


答案 1
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

答案 2

您可以使用array_keys计数来执行此操作。

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

输出:

3