phparraysmultidimensional-arraycountarray-column

Count number of non-null values in each column of a 2d array


Let's say I have an array:

[
  {0:1, 1:5, 3:null},
  {0:4, 1:null, 3:null},
  {0:null, 1:5, 3:5}
]

I want to count non-null values per associative key so that my expected output is:

[{0:2, 1:2, 3:1}]

Solution

  • Try this it will find the sum even if one key exists in only one array as well. This will find both the sum and the counts.

    <?php
    
    $arr = [
      [0 => 1, 1 => 5, 3 => null],
      [0 => 4, 1 => null, 3 => null],
      [0 => null, 1 => 5, 3 => 5]
    ];
    $out   = [];
    $count = [];
    foreach ( $arr as $key => $value) {
        # code...
        foreach ( $value as $k => $v) {
          if(NULL != $v) {
             $count[$k] = isset($count[$k]) ? ($count[$k] + 1) : 1;
          }
    
          $v       = (NULL === $v) ? 0 : $v;
          $out[$k] = isset($out[$k]) ? ($out[$k] + $v) : $v;
    
       }
    
    }
    echo '<pre>';
    echo "Sum array is : ";
    print_r($out);
    echo '</pre>';
    
    echo '<pre>';
    echo "Count array is : ";
    print_r($count);
    echo '</pre>';
    

    Will gives the output

    Sum array is : 
    Array
    (
        [0] => 5
        [1] => 10
        [3] => 5
    )
    
    Count array is : 
    Array
    (
        [0] => 2
        [1] => 2
        [3] => 1
    )
    

    And for the input array commented below

        $arr = [ 
        [0 => null, 1 => null, 3 => null], 
        [0 => 4, 1 => null, 3 => null], 
        [0 => null, 1 => 5, 3 => 5] 
    ];
    

    Will give

    Sum array is : 
    Array
    (
        [0] => 4
        [1] => 5
        [3] => 5
    )
    
    Count array is : 
    Array
    (
        [0] => 1
        [1] => 1
        [3] => 1
    )
    

    If this is not what you want give the expected output for the commented array as well.