5

Current array:

Array (
    [name] => Array (
        [name1] => Array (
            [0] => some value1
        )
        [name2] => Array (
            [0] => some value2
        )
        [name3] => Array (
            [0] =>
        )
) 

Wanted array:

Array (
    [name] => Array (
        [name1] => Array (
            [0] => some value1
        )
        [name2] => Array (
            [0] => some value2
        )
) 

Since name3[0] doesn't contain any value, it needs to be removed. From what I read, I should use array_filter for this, but I can't get it to work.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
RhymeGuy
  • 2,102
  • 5
  • 32
  • 62

3 Answers3

5

You need to feed array_filter a predicate (function) that determines if the [0] sub-element of each array element is empty or not. So:

$array = array_filter($array, function($item) { return !empty($item[0]); });

Be aware that empty is not very picky: it will result in removing any item whose [0] sub-element is the empty string, false, null, 0 or "0" -- it will also remove items that do not have a [0] sub-element at all. If you need something more surgically targeted the test needs to be fine-tuned.

Jon
  • 428,835
  • 81
  • 738
  • 806
5

Recursive function, it will remove all empty values and empty arrays from input array:

//clean all empty values from array
function cleanArray($array)
{
    if (is_array($array))
    {
        foreach ($array as $key => $sub_array)
        {
            $result = cleanArray($sub_array);
            if ($result === false)
            {
                unset($array[$key]);
            }
            else
            {
                $array[$key] = $result;
            }
        }
    }

    if (empty($array))
    {
        return false;
    }

    return $array;
}

I have tested it on this example, it works no matter how deep is array:

$array = array(
    'name' => array(
        'name1' => array(0 => 1),
        'name2' => array(0 => 3, 1 => array(5 => 0, 1 => 5)),
        'name3' => array(0 => '')
    )
);

Hope this helps :)

2

Could be accomplished using a recursive function:

$arr = array('test', array('',0,'test'), array('',''));

print_r(clean_array($arr));

function clean_array($array, $isRepeat = false) {
    foreach ($array as $key => $value) {
        if ($value === null || $value === '') { unset($array[$key]); }
        else if (is_array($value)) {
            if (empty($value)) { unset($array[$key]); }
            else $array[$key] = clean_array($value);
        }
    }
    if (!$isRepeat) {
        $array = clean_array($array,true);
    }
    return $array;
}
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
  • What is the point of the $isRepeat flag? Also adding a trim($value) for the comparison of trim($value) === '' might be useful. – aruuuuu Dec 24 '15 at 19:12