用PHP计算数组中特定值的出现 [英] Counting occurrence of specific value in an Array with PHP

查看:63
本文介绍了用PHP计算数组中特定值的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个本机PHP函数,该函数将允许我计算数组中特定值的出现次数.我熟悉array_count_values()函数,但是该函数返回数组中所有值的计数.有没有允许您传递值并仅返回该特定值的实例计数的函数?例如:

I am trying to find a native PHP function that will allow me to count the number of occurrences of a particular value in an array. I am familiar with the array_count_values() function, but that returns the count of all values in an array. Is there a function that allows you to pass the value and just return the instance count for that particular value? For example:

$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);

$instances = some_native_function(6, $array);  //$instances will be equal to 4

我知道如何创建自己的功能,但是为什么要重新发明轮子呢?

I know how to create my own function, but why re-invent the wheel?

推荐答案

function array_count_values_of($value, $array) {
    $counts = array_count_values($array);
    return $counts[$value];
}

不是 native ,但是来吧,它很简单. ;-)

Not native, but come on, it's simple enough. ;-)

或者:

echo count(array_filter($array, function ($n) { return $n == 6; }));

或者:

echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);

或者:

echo count(array_keys($array, 6));

这篇关于用PHP计算数组中特定值的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆