PHP Count Number of True Values in a Boolean Array(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 布尔数组中真值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP Count 布尔数组中真值的数量


基础教程推荐
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的PDF导出 2022-01-01
- php中的foreach复选框POST 2021-01-01