Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude null values from COUNT in array

Tags:

php

How can I exclude null values from a count on an array? since count always includes null values in the counting!

like image 643
ProXamer Avatar asked Sep 17 '25 03:09

ProXamer


2 Answers

count(array_filter($array, function($x) {return !is_null($x); })
like image 79
PenguinCoder Avatar answered Sep 18 '25 17:09

PenguinCoder


function count_nonnull($a) {
    $total = 0;
    foreach ($a as $elt) {
        if (!is_null($elt)) {
            $total++;
        }
    }
    return $total;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!