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

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


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


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 reassignmentforeach($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);}