16

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"

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39

3 Answers3

58

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);
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
  • 1
    thanks, did miss what array_map was returning - but pealse could you specify why would you concider array_walk as a wrong function? – Jaak Kütt Feb 12 '13 at 09:08
  • 9
    if you read the [manual](http://php.net/array-walk) you will see that array_walk just **calls** a function with each of the values (and keys) of an array. So it would have the same effect as: `trim('test_data_1 ', 0); trim('test_data_2 ', 1)` - no assignments, no side effects (and a wrong second parameter for trim, by the way). You *could* of course write your own function for array_walk, that then trims the actual array element. – Fabian Schmengler Feb 12 '13 at 09:12
4

For array_walk to modify the items (values) in the array, the callback must be a function that takes its first parameter by reference and modifies it (which is not the case of plain trim), so your code would become:

$a=array('test_data_1 ','test_data_2');
array_walk($a, function (&$value) { $value = trim($value); }); // by-reference modification
// (no array_map)
foreach($a AS $b){
    var_dump($b);
}

Alternatively, with array_map you must reassign the array with the return value, so your code would become:

$a=array('test_data_1 ','test_data_2');
// (no array_walk)
$a = array_map('trim', $a); // array reassignment
foreach($a AS $b){
    var_dump($b);
}
0

array_map return a new array, try this

$a=array('test_data_1 ','test_data_2');
array_walk($a, 'trim');
$a = array_map('trim', $a);
foreach($a AS $b){
    var_dump($b);
}
silly
  • 7,789
  • 2
  • 24
  • 37