Removing empty values from POST array?

I am trying to remove empty values from the entire POST array but I can’t get it too work :frowning:

My array looks like this:

array(2) {   ["eirepanel_inline_ads_options_saved"]=>   string(4) "true"   ["eirepanel_inline_ads_options_name"]=>   array(5) {     [0]=>     string(5) "rtyrt"     [1]=>     string(0) ""     [2]=>     string(0) ""     [3]=>     string(0) ""     [4]=>     string(0) ""   } }                          

and here is my code


$post_data = $_POST;
   
function filter_post($value)
{ 
       if ($value !='')
      {
            return $value;
      }  
}
$new_array=array_filter($post_data,'filter_post');
        
var_dump($new_array);

Any help, very much appreciated!

Is array_filter on its own insufficient?


<?php
$array = array(
  '',
  1,
  2,
  'foo' => 'bar',
  'ying' => '',
  true,
  false,
  null
);

print_r(
  array_filter($array)
);

/*
Array
(
  [1] => 1
  [2] => 2
  [foo] => bar
  [3] => 1
)
*/

Thanks Anthony,

How do you deal with the POST array. My code works with a “normal” array but not $_POST

$_POST is a normal array. :slight_smile:


$_POST = array_filter($_POST);

If by “normal” you mean one dimensional then array_filter will work, however, the array you’re showing us is multidimensional so array_filter on its own won’t cover all of the elements.

The comments below the PHP manual entry for array_filter have an example that may help:

array_filter multidimensional array

Once again, thanks for taking the time to respond. No luck with this though :injured:

array(2) {   ["eirepanel_inline_ads_options_saved"]=>   string(4) "true"   ["eirepanel_inline_ads_options_name"]=>   array(3) {     [0]=>     string(5) "rtyrt"     [1]=>     [B]string(0) ""[/B]     [2]=>     [B]string(0) "" [/B]  } }                          

function removeEmptyRecursive($arr)
{
   foreach($arr as $k=>$v)
   {
       if (is_array($v))
       {
            $v=$arr[$k]=removeEmptyRecursive($arr[$k]);
       }
       if ($v==false)
       {
            unset($arr[$k]);
       }
   }
   return $arr;
}

$a=array(
  '',
  'a'=>array(
    '',
    'a'
  ),
  'b'=>array(
    '',
    ''
  ),
  'c'
);

var_dump(removeEmptyRecursive($a));

/**
array
  'a' => 
    array
      1 => string 'a' (length=1)
  1 => string 'c' (length=1)
**/

:slight_smile:

@[COLOR=#0000ff][B]ScallioXTX[/B][/COLOR] Perfect!!! Thank you mate, so much appreciated :slight_smile:

EDIT: Why use this beast of a function and can you explain the recursion aspect to it?.

Also, why didn’t Anthony’s solution work for the POST array but would for an array I made (with empty spaces)? :slight_smile: