phptrimarray-maparray-walk

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"


Solution

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