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"

3 Answers 3

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);
2
  • 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, 2013 at 9:08
  • 9
    if you read the manual 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. Feb 12, 2013 at 9: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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.