Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map and trim not trimming white space from values

Tags:

arrays

php

trim

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);
like image 840
Anagio Avatar asked Aug 16 '13 14:08

Anagio


People also ask

How to remove whitespace from array in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.


1 Answers

$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);
like image 145
Hanky Panky Avatar answered Sep 24 '22 23:09

Hanky Panky