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 布尔数组中真值的数量


- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01