How to Remove Whitespaces From All Values of a PHP Array?

To trim whitespace characters from all elements of an array in PHP, you can use the array_map() function along with trim() like so:

array_map('trim', $array)

This would apply trim() to each element of the array. By default, the trim() function will remove the following whitespace characters from a string:

  • " " (ASCII 32 / 0x20) — an ordinary space;
  • "\t" (ASCII 9 / 0x09) — a tab;
  • "\n" (ASCII 10 / 0x0A) — a new line (line feed);
  • "\r" (ASCII 13 / 0x0D) — a carriage return;
  • "\0" (ASCII 0 / 0x00) — the NUL-byte;
  • "\v" (ASCII 11 / 0x0B) — a vertical tab.

For example:

$arr = [ '  foo', 'bar' . chr(0x0A), chr(0x09) . 'baz' ];

$trimmedArr = array_map('trim', $arr);
var_dump($trimmedArr); // ['foo', 'bar', 'baz']

You can, of course, use a loop as well to achieve the same, for example, like so:

$arr = [ '  foo', 'bar' . chr(0x0A), chr(0x09) . 'baz' ];
$trimmedArr = [];

foreach ($arr as $item) {
    $trimmedArr[] = trim($item);
}

var_dump($trimmedArr); // ['foo', 'bar', 'baz']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.