Trim whitespace characters from array values in PHP
This article demonstrates how to trim whitespace characters from the array values in PHP. The whitespace is composed of space, tab, line feed, carriage return, form feed, and vertical tab.
1. Using array_map()
function
The array_map() function applies a callback function to each array element. It returns a new array containing the results of applying the callback to each value in the array. To remove all the leading and trailing whitespace from the array values, you can use the trim()
function as a callback to the array_map()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $array = array('a', 'b ', ' c '); var_export($array); /* array ( 0 => 'a', 1 => 'b ', 2 => ' c ', ) */ $trimmed_array = array_map('trim', $array); var_export($trimmed_array); /* array ( 0 => 'a', 1 => 'b', 2 => 'c', ) */ ?> |
2. Using array_walk()
function
The above solution applies a callback to all values and returns a new array with the updated values. If you want to in-place modify the array, you can walk through the entire array and apply a user-defined callback function to each encountered element using the array_walk() function.
The callback function accepts the value of the array member as a parameter, optionally followed by the key. However, array_walk()
cannot be used to alter the keys of the array, only its values can be changed. The following example demonstrates the usage of array_walk()
to trim an array using an anonymous function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $array = array('a', 'b ', ' c '); var_export($array); /* array ( 0 => 'a', 1 => 'b ', 2 => ' c ', ) */ array_walk($array, function (&$value) { $value = trim($value); }); var_export($array); /* array ( 0 => 'a', 1 => 'b', 2 => 'c', ) */ ?> |
That’s all about trimming whitespace characters from the array values in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)