Monday, September 23, 2013

How to strip whitespace from an array using PHP?

You can strip white space from an array by using a combination of following php functions.

  • array_filter — Filters elements of an array using a callback function
  • array_map — Applies the callback to the elements of the given arrays
  • trim — Strip whitespace (or other characters) from the beginning and end of a string

Syntax
array_filter(array_map('trim', $array));
This will remove all whitespace from the sides (but not between chars). And it will remove any entries of input equal to FALSE (e.g. 0, 0.00, null, false, …)

For example
$array = array(' foo ', 'bar ', ' baz', '    ', '', 'foo bar');
$array = array_filter(array_map('trim', $array));
print_r($array);

// Output
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [5] => foo bar
)

Source: http://stackoverflow.com/a/3384083

No comments:

Post a Comment