Search code examples
phparraysfilteringwhitespace

Remove array elements which contain only whitespaces?


I have an array like this:

$arr = [
   'red',
   '   ',
   'blue',
   '       ',
   'green',
   '  ',
   'white',
   '    ',
   'black',
   '           '
];

I'm trying to remove all items which are just containing whitespace(s).

This is the expected result:

[
    'red',
    'blue',
    'green',
    'white',
    'black'
]

I can do that if those whitespaces item be empty. So I can use $arr = array_filter($arr);. But in this case, because there are whitespaces instead of nothing, array_filter() isn't useful. Is there any approach to do that?


Solution

  • You could just couple it with array_map using trim:

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

    This doesn't reindex the keys though, if you want you could just use array_values:

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