Recursively remove empty elements and subarrays from a multi-dimensional array

后端 未结 6 2060
暖寄归人
暖寄归人 2020-11-27 19:19

I can\'t seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.

My input array may look like this: <

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 19:27

    The accepted answer does not do exactly what the OP asked. If you want to recursively remove ALL values that evaluate to false including empty arrays then use the following function:

    function array_trim($input) {
        return is_array($input) ? array_filter($input, 
            function (& $value) { return $value = array_trim($value); }
        ) : $input;
    }
    

    Or you could change the return condition according to your needs, for example:

    { return !is_array($value) or $value = array_trim($value); }
    

    If you only want to remove empty arrays. Or you can change the condition to only test for "" or false or null, etc...

提交回复
热议问题