5

I'm using array_map to trim all my array values but I need to pass a third parameter because I need to more than just trim whitespaces so I'm passing in a third parameter. Basically I want to trim all array values of whitespaces, single quotes, and double quotes.

I have a utility class where I created the function and it looks like this:

public function convertToArray($string, $trim = false) {
    $split = explode(",", $string);

    if($trim) {
        $split = array_map("trim", $split, array(" '\""));
    }

    return $split;
}

Somehow I can't make this work though. I can still see double quotes in the result even though I followed the answer here.

I even tried

if($trim) {
    $split = array_map("trim", $split);
    $split = array_map("trim", $split, array("'"));
    $split = array_map("trim", $split, array('"'));
}

but I still get the same result.

Community
  • 1
  • 1
dokgu
  • 4,957
  • 3
  • 39
  • 77
  • On a side-note for people who just came here --- it's better to use `str_getcsv` rather than `explode` if your string contains the delimeter inside quotes as mentioned [in this SO question](http://stackoverflow.com/questions/5132533/php-how-can-i-explode-a-string-by-commas-but-not-wheres-the-commas-are-within). – dokgu Dec 22 '16 at 15:54

3 Answers3

18

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);
Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25
  • Is there a reason why you changed the second parameter of `trim` to single quotes? – dokgu Dec 22 '16 at 15:41
  • 1
    Just my personal preference. I prefer single quotes over double quotes, as they treat everything literally and don't parse variables, among other things. In this case it doesn't make a difference, you have to escape one of the characters with backslash anyway. – Bartosz Zasada Dec 22 '16 at 15:48
2

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);
martindilling
  • 2,839
  • 3
  • 16
  • 13
0

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'\""); 
});
Brandon Hill
  • 1,782
  • 14
  • 12