2

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.

3
  • 2
    array_filter is the droid you're looking for Commented Jul 18, 2017 at 12:42
  • 2
    check for empty value too with null comparison Commented Jul 18, 2017 at 12:43
  • Replace the array in the question with the output of var_export($myArray) or provide a sandbox. Commented Jul 18, 2017 at 12:48

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice function! Work fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.