Question

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"

Was it helpful?

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

OTHER TIPS

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

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top