Is this technique necessary when using array_walk()
I'm working on code that wasn't written by me. I see that the developer w开发者_如何学运维anted to trim all elements of the array and used array_walk()
but what's the point of declaring a _trim
function that all it does is use the standard trim()
?
array_walk($arr, '_trim');
function _trim(&$value)
{
$value = trim($value);
}
Yes, for array_walk it would be necessary, because of call-by-reference. In this case it would be in my opinion better to use array_map:
$arr = array_map('trim', $arr);
Yes. Like the manual says:
If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.
It would perhaps be easier to use array_map
:
$arr = array_map('trim', $arr);
You can also use anonymous function to trim array elements. The advantage over array_map
is that you can use array_walk
recursively:
array_walk_recursive($arr, function(&$v) {
$v = trim($v);
});
trim
returns a trimmed value, it doesn't modify the passed value.
array_walk($arr, 'trim');
if you execute array_walk with a normal trim you'll see that it doesn't do anything:
精彩评论