How to count non-empty entries in a PHP array?

前端 未结 3 1230
Happy的楠姐
Happy的楠姐 2020-12-01 06:09

Consider:

[name] => Array ( [1] => name#1
                  [2] => name#2
                  [3] => name#3
                  [4] => name#4
             


        
相关标签:
3条回答
  • 2020-12-01 06:40

    Here's a simple calculation function:

    function non_empty(array $a) {
        return array_sum(array_map(function($b) {return empty($b) ? 0 : 1;}, $a));
    }
    

    This will preserve array indexes if your form handling function needs them, like when you're associating the third input on name to the third value of another input set, and there are empty inputs in between them.

    0 讨论(0)
  • 2020-12-01 06:41

    You can use array_filter to only keep the values that are “truthy” in the array, like this:

    array_filter($array);
    

    If you explicitly want only non-empty, or if your filter function is more complex:

    array_filter($array, function($x) { return !empty($x); });
    # function(){} only works in in php >5.3, otherwise use create_function
    

    So, to count only non-empty items, the same way as if you called empty(item) on each of them:

    count(array_filter($array, function($x) { return !empty($x); }));
    
    0 讨论(0)
  • 2020-12-01 06:44
    count(array_filter($name));
    
    0 讨论(0)
提交回复
热议问题