PHP array_map trim + parameters

馋奶兔 提交于 2019-12-01 06:12:11

array_map takes a function that takes only one parameter. If you want to map your array with trim() with subsequent parameters different from the default ones, you have to wrap it with an anonymous function:

$split = array_map(function($item) {
    return trim($item, ' \'"');
}, $split);

I think you would need to use an anonymous function for that :)

$split = array_map(function ($value) {
    return trim($value, " '\"");
}, $split);

Just because this was exactly the same as the other answer, here is an alternative. This approach could be useful if this is an operation you're going to need in many different places ;)

function trim_spaces_and_quotes($value) {
    return trim($value, " '\"");
}

$split = array_map('trim_spaces_and_quotes', $split);

I'd use array_walk, and you just have to append your additional characters to the existing defaults (from the docs):

array_walk($string_arr_to_trim, function (&$v) {
  $v = trim($v, " \t\n\r\0\x0B'\""); 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!