I want to remove NULL
, FALSE
and \'\'
values .
I used array_filter
but it removes the 0
\' s also.
One-liners are always nice.
$clean_array = array_diff(array_map('trim', $my_array), array('', NULL, FALSE));
Explanation:
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.array_diff
: An array of items that you would like to remove from $my_array
.''
, 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(''));