Search code examples
phparraystrim

array_map and trim not trimming white space from values


This function below returns a string of values comma separated

$key_1_value = get_post_meta(422,'keywords',true);

The output in my browser looks like red, white, blue, blue two , green, yellow, purple, magenta , cyan, black

I'm trying to trim the white space before and after all values.

So I used this code to try and trim the whitespace but it's still there. Why won't this trim the values?

$test = array($key_1_value);
$trimmed_array=array_map('trim',$test);
print_r($trimmed_array);

Solution

  • $key_1_value is a string representation and not an array or a string with quoted values, you have to explode it into array items, and not just put it inside an array call, then it becomes a proper array

    $test = explode(",", $key_1_value);
    $trimmed_array = array_map('trim', $test);
    print_r($trimmed_array);