简体   繁体   中英

How to count elements inside array/object on PHP?

I have this array being sent to my view

Array
(
    [0] => stdClass Object
        (
            [emg_id] => 2
            [fkit] => 1
            [door] => 
        )

)

I would like to count how many elements are empty, NULL, or '0'.

I tried using count but it always returns '1', instead of counting all of the elements, so I can later determine which satisfy my conditions above.

Any ideas what I'm doing wrong?

// number of "null" elements
echo count(array_filter((array) $array[0], 'is_null'));

There are some other is_*() -functions built-in, that may help you for example to count the number of strings (and so on).

To test, if an element is (eg) 0 , I suggest to use an anonymous function

echo count(array_filter((array) $array[0], function ($item) {
  return $item === 0;
}));

The other cases are similar.

loop through them and count.

function loopMe($array, $value) {
    $num = 0;
    foreach($array as $key=>$val) {
        if($val == $value)
        $num++;
    }
    return $num;
}


$ar = array (
    array (
        "emg_id" => 2
        "fkit" => 1
        "door" => null));
$num = loopMe($ar[0], null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM