1

I have an array as such:

$d = [
    0 => [
        0 => 'lorem',
        1 => 'dorem',
        3 => '',
        4 => 'ipsum'
    ],
    1 => [
        0 => 'test',
        1 => 'rere',
        3 => '',
        4 => 'youp'
    ]
];

My issue is that I need to remove empty values from the array. How would I go about using array_filter in removing such empty keys/values from the multidimensional array? I have over 162 sets of arrays totaling 62 each, so this problem is via a large data set.

Zach Smith
  • 5,490
  • 26
  • 84
  • 139

2 Answers2

0

For 2D arrays this method will work: array_map('array_filter', $d);

For more nested levels you can use pointers or recursive functions:

$result = clean($d);

function clean($array)
{
    foreach ($array as $index => $item)
    {
        if (is_array($item))
        {
            $array[$index] = clean($item);
        }

        if (!$array[$index])
        {
            unset($array[$index]);
        }
    }

    return $array;
}
user1597430
  • 1,138
  • 1
  • 7
  • 14
0

Use array_filter like this, demo

foreach($d as &$array){
    $array = array_filter($array);
}
var_dump($d);

LF00
  • 27,015
  • 29
  • 156
  • 295