Remove NULL, FALSE, and '' - but not 0 - from a PHP array

后端 未结 9 2326
一生所求
一生所求 2020-12-09 02:15

I want to remove NULL, FALSE and \'\' values .

I used array_filter but it removes the 0\' s also.

9条回答
  •  温柔的废话
    2020-12-09 02:34

    One-liners are always nice.

    $clean_array = array_diff(array_map('trim', $my_array), array('', NULL, FALSE));
    

    Explanation:

    • 1st parameter of array_diff: The trimmed version of $my_array. Using array_map, surrounding whitespace is trimmed from every element via the trim function. It is good to use the trimmed version in case an element contains a string that is nothing but whitespace (i.e. tabs, spaces), which I assume would also want to be removed. You could just as easily use $my_array for the 1st parameter if you don't want to trim the elements.
    • 2nd parameter of array_diff: An array of items that you would like to remove from $my_array.
    • Output: An array of elements that are contained in the 1st array that are not also contained in the 2nd array. In this case, because '', NULL, and FALSE are within the 2nd array, they can never be returned by array_diff.

    EDIT:

    It turns out you don't need to have NULL and FALSE in the 2nd array. Instead you can just have '', and it will work the same way:

    $clean_array = array_diff(array_map('trim', $my_array), array(''));
    

提交回复
热议问题