Matt Elhotiby
Matt Elhotiby

Reputation: 44066

How do I remove the nulls out of the inner PHP array

I have an array from which I need to remove null values:

 [227] => Array
    (
        [0] => 3
        [1] => 8
        [2] => 
        [3] => 
        [4] => 1
    )

)

I tried array_filter($quantity);

and also

foreach ($quantity as $key => $value) {
    if (is_null($value) || $value=="") {
        unset($quantity);
    }
}

and even tried the foreach with $quantity[0] and got Undefined offset 0. Any ideas?

UPDATE

This works but what if i dont have the 227

foreach ($quantityval[227] as $key => $value) {
   if (is_null($value) || trim($value)=="") {  
      unset($quantityval[227][$key]);
  }
 }

Upvotes: 1

Views: 131

Answers (4)

EPB
EPB

Reputation: 4029

I use something like this for situations like that:

<?php
function filter_empty_recursive($arr)
{
    $keys = array_keys($arr);
    foreach($keys as $key)
    {
        if(is_array($arr[$key]))
        {
            $arr[$key] = filter_empty_recursive($arr[$key]);
        }
        else if(empty($arr[$key]))
        {
             unset($arr[$key]);
        }
   }
   return $arr;
}

It's a recursive function (so it can be a little brutal on memory with large nested array trees, and this particular one cannot handle infinite recursion (i.e.: circular reference).) But with a non-infinite recursion, and reasonably sized nested array trees, it should work pretty well. It can also be expanded to handle nested object properties as well, but that seemed outside scope. The part where it decides if it's empty is that if(empty()) so you can change that back to that is_null or empty string block.

(Edit: Adding really Low level explanation: loops through the array, if it finds an array inside of that array, it calls itself and repeats the process.)

Upvotes: 0

Rolando Cruz
Rolando Cruz

Reputation: 2784

You updated solution works. The part about the hardcoded 227 is because $quantity is a multi-dimensional array (the extra closing parenthesis hinted that too). You need to do nested foreach for that.

foreach($bigArray as $bigKey => $smallArray)
{
  foreach($smallArray as $smallKey => $value)
  {
     if(is_null($value) || $value == "")
       unset($bigArray[$bigKey][$smallKey]);
  }
}

Upvotes: 1

drinkdecaf
drinkdecaf

Reputation: 405

This looks like a nested array -- your foreach statement looks correct, but needs to check the inner arrays:

foreach ($quantity as $key => $item)
    foreach ($item as $key2 => $item2) {
        if (is_null($item2) || $item2=="") {
            unset($quantity[$key][$key2]);
        }
    }
}

Upvotes: 2

Brad Mace
Brad Mace

Reputation: 27886

You appear to have values that are all white-space -- either regular spaces or possibly unicode characters. Try trim($value) == "".

If that doesn't work array_filter($array, "is_integer"); may do the trick.

Upvotes: 1

Related Questions