PHP Count 布尔数组中真值的数量 [英] PHP Count Number of True Values in a Boolean Array

查看:27
本文介绍了PHP Count 布尔数组中真值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联数组,我需要在其中计算布尔真值的数量.

I have an associative array in which I need to count the number of boolean true values within.

最终结果是创建一个 if 语句,当数组中只存在一个真值时,该语句将返回真值.如果数组中有多个真值,或者数组中没有真值,则需要返回 false.

The end result is to create an if statement in which would return true when only one true value exists within the array. It would need to return false if there are more then one true values within the array, or if there are no true values within the array.

我知道最好的方法是以某种形式使用 count 和 in_array .我不确定这是否可行,只是在我的头顶上,但即使可行,这是最好的方法吗?

I know the best route would be to use count and in_array in some form. I'm not sure this would work, just off the top of my head but even if it does, is this the best way?

$array(a->true,b->false,c->true)    

if (count(in_array(true,$array,true)) == 1)
{
    return true
}
else
{
    return false
}

推荐答案

我会使用 array_filter.

I would use array_filter.

$array = array(true, true, false, false);
echo count(array_filter($array));
//outputs: 2

http://codepad.viper-7.com/ntmPVY

Array_filter 将删除 false-y (value == false) 的值.那就来数一数吧.如果您需要根据某些特殊值进行过滤,例如您正在查找特定值,则 array_filter 接受一个可选的第二个参数,该参数是您可以定义的函数,用于返回值是 true(未过滤)还是 false(过滤掉)).

Array_filter will remove values that are false-y (value == false). Then just get a count. If you need to filter based on some special value, like if you are looking for a specific value, array_filter accepts an optional second parameter that is a function you can define to return whether a value is true (not filtered) or false (filtered out).

这篇关于PHP Count 布尔数组中真值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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