1

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?

0

2 Answers 2

4
// 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 (e.g.) 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.

Sign up to request clarification or add additional context in comments.

4 Comments

thx @kingcrunch -- how about the 'is_null' in your first example: I get an error message saying the second parameter should be long, string given -- is your 'is_null' just a placeholder?
:) - good xkcd BTW - looks like 'empty' also returns an error -- "The second argument, 'empty', should be a valid callback"
... empty is a language construct -.- However, the idea is clear? :D
yes thanks for helping -- looks like using array_filter without callback covers most of my needs
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.