How to remove empty values from multidimensional array in PHP?

依然范特西╮ 提交于 2019-11-27 23:53:29
Alastair F

Bit late, but may help someone looking for same answer. I used this very simple approach to;

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );

The following function worked for my case. We can use a simple recursive function to remove all empty elements from the multidimensional PHP array:

function array_filter_recursive($input){
    foreach ($input as &$value){
        if (is_array($value)){
            $value = array_filter_recursive($value);
        }
    }
    return array_filter($input);
}

Then we just need to call this function:

$myArray = array_filter_recursive($myArray);

Not sure if this is exactly what your looking for.

function array_remove_null($array) {
    foreach ($array as $key => $value)
    {
        if(is_null($value))
            unset($array[$key]);
        if(is_array($value))
            $array[$key] = array_remove_null($value);
    }
    return $array;
}

Update (corrections):

function array_remove_null($array) {
    foreach ($array as $key => $value)
    {
        if(is_null($value))
            unset($array[$key]);
        if(is_string($value) && empty($value))
            unset($array[$key]);
        if(is_array($value))
            $array[$key] = array_remove_null($value);
        if(isset($array[$key]) && count($array[$key])==0)
            unset($array[$key]);
    }
    return $array;
}

I'm sure better checking and making this more robust might help the solution.

use array_map() for filter every array in $array:

$newArray = array_map('array_filter', $array);

Here's demo

$newArray = array_map('array_filter', $array);

This sintax it's work and very help full thank's guys ..

Use array_filter with array_map like below:

$arr=array_filter(array_map('array_filter', $arr));

This removes all items with null values recursively on multideminsional arrays. Works on PHP >= 5.6. If you want to remove all "empty" values, replace !is_null($value) with !empty($value).

function recursivelyRemoveItemsWithNullValuesFromArray(array $data = []): array
{
    $data = array_map(function($value) {
        return is_array($value) ? recursivelyRemoveItemsWithNullValuesFromArray($value) : $value;
    }, $data);

    return array_filter($data, function($value) {
        return !is_null($value);
    });
}

Because the subarrays in your array only have one element each, you can simplify the approach using either of the two following methods. The logical advantage is in avoiding the functional iterator (array_filter) on the second level elements. This is why current() is more suitable for this question/page.

Code: (Demo)

$quantities=[
    10=>['25.00'=>1],
    9=>['30.00'=>3],
    8=>['30.00'=>4],
    12=>['35.00'=>null],
    1=>['30.00'=>''],
    2=>['30.00'=>null]
];

var_export(array_filter($quantities,function($a){return strlen(current($a));}));

OR

foreach($quantities as $key=>$sub){  // could be done "by reference" but that impacts code stability
    if(!strlen(current($sub))){  // if subarray value has no length
        unset($quantities[$key]);
    }
}
var_export($quantities);

Both output the same result (which purposely removes empty values and preserves 0 values)

array (
  10 => 
  array (
    '25.00' => 1,
  ),
  9 => 
  array (
    '30.00' => 3,
  ),
  8 => 
  array (
    '30.00' => 4,
  ),
)

In the above methods, strlen() is used to check the 2nd level elements because the OP only listed integers as the "non-empty" values. Future SO readers may have different requirements based on the elements possibly holding false, null, '0', 0, etc. Suitable replacement functions for strlen() may be: any of the "is_" functions, empty(), any of the "ctype" functions, and many more.

If the OP's 2nd level array held more than one element AND the OP wanted to remove all zero-ish, false-y, empty, null elements (meaning zeros are not wanted or guaranteed not to occur), then Alastair F's answer would be the best choice.

If the OP's input array had an unknown number of levels AND zero-ish/false-y/empty/null elements should be removed, then Reza Mamun's answer is a logical, recursive approach.

My point being (and my motivation behind spending so much time and care to answer this question) that array_filter() is greedy and if you aren't aware of this default behavior, your project may silently output incorrect information. I hope this explanation saves programmers some time and strife.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!