使用给定值计算数组中的值数 [英] Count number of values in array with a given value

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

问题描述

假设我有一个这样的数组:

Say I have an array like this:

$array = array('', '', 'other', '', 'other');

如何计算具有给定值的数字(在示例空白中)?

How can I count the number with a given value (in the example blank)?

并且有效地做到这一点?(大约十几个数组,每个数组有数百个元素)此示例超时(超过 30 秒):

And do it efficiently? (for about a dozen arrays with hundreds of elements each) This example times out (over 30 sec):

function without($array) {
    $counter = 0;
    for($i = 0, $e = count($array); $i < $e; $i++) {
        if(empty($array[$i])) {
            $counter += 1;
        }
    }
    return $counter;
}

在这种情况下,空白元素的数量是 3.

In this case the number of blank elements is 3.

推荐答案

如何使用 array_count _values 以获得一个数组,其中的所有内容都为您计数?

How about using array_count _values to get an array with everything counted for you?

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

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