2

I have an array, $row2.

In $row2 two arrays are present. The output of $row2 is:

Array
(
    [0] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2
            [col2] => 2
            [col3] =>
            [col4] =>
            [col5] =>
            [Type] => customtbl
            [Invoice_term] =>
            [Qoute] =>
            [Rate_per_hour] =>
            [Total] =>
        )

    [1] => Array
        (
            [Proposal_id] => 9
            [row] => 2
            [col1] => 3
            [col2] => 4
            [col3] =>
            [col4] =>
            [col5] =>
            [Type] => customtbl
            [Invoice_term] =>
            [Qoute] =>
            [Rate_per_hour] =>
            [Total] =>
        )

)

I want to remove null elements from the array, but I can't do this.

I tried the following methods:

array_filter($row2);
array_filter($row2, function($var){return !is_null($var);});
array_diff($rows2, array("null", ""));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dani
  • 43
  • 6

2 Answers2

1

I've an one liner solution to filter out null values from multidimensional array if you use array_map along with array_filter,

    $array = [
    ['Proposal_id' => 9,
     'row' => 1,
     'col1' => 2, 
     'col2' => 2, 
     'col3' => null,
     'col4' => null,
     'col5' =>  null,
     'Type' => 'customtbl',
     'Invoice_term' => null,  
     'Qoute' => null,
     'Rate_per_hour' => null,  
     'Total' => null,
    ],
    [   
        'Proposal_id' => 9,
        'row' => 1,
        'col1' => 2, 
        'col2' => 2 ,
        'col3' => null,
        'col4' => null,
        'col5' =>  null,
        'Type' => 'customtbl',
        'Invoice_term' => null,  
        'Qoute' => null,
        'Rate_per_hour' => null,  
        'Total' => null,
    ]
];
$af = array_filter(array_map('array_filter', $array));
print '<pre>';
print_r($af);
print '</pre>';

Output:

 Array
(
    [0] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2
            [col2] => 2
            [Type] => customtbl
        )

    [1] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2
            [col2] => 2
            [Type] => customtbl
        )

)

DEMO : https://eval.in/975240

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

Use array_filter within array_map. Just remember you may want to run a different conditional rather than if($value) as this will validate against not only nulls, but zeros and empty strings.

array_map(function($var) {
    return array_filter($var, function($value) {
        if ( !is_null($value) )
            return $value;
    });
},$row2);
Napoli
  • 1,389
  • 2
  • 15
  • 26