jumpman8947
jumpman8947

Reputation: 581

Eliminating null value nested array php

I have an array and contents nested inside the original array. The contents of the array look like-

$myArray

[0] => Array(
[ID] => 1
[Fruit] => Apple
[State] => Ohio
[description]
   Array(
     [0] => This is sample description
     [1] => This is sample description 2
     [2] => 
     [3] => 
     [4] => 


)
 [price]
   Array(
     [0] => 20
     [1] => 15
     [2] => 
     [3] => 
     [4] => 
)
[1] => Array(
[ID] => 1
[Fruit] => Apple
[State] => Ohio
[description]
   Array(
     [0] => This is sample description
     [1] => This is sample description 2
     [2] => 
     [3] => 
     [4] => 
)
[price]
   Array(
     [0] => 20
     [1] => 15
     [2] => 
     [3] => 
     [4] => 
)

I want to get rid of the null values in the nested array. When i use the following:

$newArray = array();
foreach ($firstArray as $row){
    if ($row !== null)
        $newArray[] = $row;

}
echo $newArray;

The new array does not get rid of the null values in the array.

Upvotes: 2

Views: 146

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You can do it like below:-

function array_filter_to_each_sub_array_recursively($input){
    foreach ($input as &$value){
        if (is_array($value)){
            $value = array_filter_to_each_sub_array_recursively($value);
        }
    }
    return array_filter($input);
}

$myArray = array_filter_to_each_sub_array_recursively($myArray);

print_r($myArray);

Output:-https://eval.in/833982

Upvotes: 3

Related Questions