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

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

问题描述

我有一个关联数组,我需要数内布尔真值的数量。

最终的结果是创建一个当阵列中只存在一个真正的价值,如果其中的语句将返回真。它需要返回false,如果在阵列中有一个以上的真正价值,或者有阵内没有真正的价值。

我知道的最佳路线是使用计数和in_array以某种形式。我不知道这会工作,只是把我的头顶部,但即使是这样,这是最好的方法是什么?

  $阵列(A->真,B>虚假,C>真)如果(计数(in_array(真,$阵列,真))== 1)
{
    返回true
}
其他
{
    返回false
}


解决方案

我会用array_filter。

  $阵列=阵列(真的,真的,假的,假的);
回声计数(array_filter($阵列));
//输出:2

HTTP://$c$cpad.viper-7.com/ntmPVY

Array_filter 将删除任何虚假-Y(价值==假)值。然后,只需获得一个计数。如果你需要基于一些特殊值过滤,就像如​​果你正在寻找一个特定的值,array_filter接受的是你可以定义返回值是否为真(非过滤)或假的函数(过滤掉一个可选的第二个参数)。

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

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.

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
}

解决方案

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 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计数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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