Why does my sample code result in the first string still having a trailing space?
$a=array('test_data_1 ','test_data_2');
array_walk($a, 'trim');
array_map('trim', $a);
foreach($a AS $b){
var_dump($b);
}
string(12) "test_data_1 " string(11) "test_data_2"
The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.
The array_walk() function is an inbuilt function in PHP. The array_walk() function walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element's keys and values are parameters in the callback function.
The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.
First, array_walk is the wrong function for your purpose at all.
Second, array_map does not change the original array but returns the mapped array. So what you need is:
$a = array_map('trim', $a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With