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

Jaak Kütt picture Jaak Kütt · Feb 12, 2013 · Viewed 14.4k times · Source

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"

Answer

Fabian Schmengler picture Fabian Schmengler · Feb 12, 2013

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);