I’d like to know the most efficient way to count array elements whose value is set True.
This is my attempt but the code gets kind of long. I’m wondering if there is a built-in function for it already or could be done in a smarter way. In this case, I’d like to know the number of elements having true in $arr[‘key’][uniquekeyname][‘check’].
$arr = array();
$arr['keys'] = array(
'a' => array('check' => true, 'otherinfo' => 'some data'),
'b' => array('check' => false, 'otherinfo' => 'some data'),
'c' => array('check' => false, 'otherinfo' => 'some data'),
'd' => array('check' => true, 'otherinfo' => 'some data'),
);
$numChecked = 0;
foreach($arr['keys'] as $key) {
if ($key['check'])
$numChecked++;
}
echo $numChecked;
The complexity will be
O(n), so looping through it is just fine.I note that maybe you want to use the triple-equal operator
===in order to compare the elements of your array totrue, since having the field check set to another value will be counted right as it is now or with==.Will output:
Whereas:
will get you
Maybe it is fine for your needs to get
==, assuming your array will always carry only true/false values.