Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't trim work as a callback for array_walk or array_map in PHP?

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"

like image 826
Jaak Kütt Avatar asked Feb 12 '13 08:02

Jaak Kütt


People also ask

What exactly is the the difference between Array_map Array_walk and Array_filter?

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.

What is array_ walk in PHP?

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.

Does array map preserve keys?

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.


1 Answers

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);
like image 154
Fabian Schmengler Avatar answered Sep 28 '22 00:09

Fabian Schmengler