7

I have a problem when using the trim() function in php.

//Suppose the input variable is null. $input = NULL; echo (trim($input)); 

As shown above, the output of the codes is empty string if the input argument if NULL. Is there any way to avoid this? It seems the trim will return empty string by default if the input is unset or NULL value.

This give me a hard time to use trim as following.

array_map('trim', $array); 

I am wondering if there's any way I can accomplish the same result instead of looping through the array. I also noticed that the trim function has second parameter, by passing the second parameter, you can avoid some charlist. but it seems not work for me.

Any ideas? Thanks.

5
  • 3
    Trim expects a string input, so PHP is trying to be helpful and is typecasting the null into an empty string. Commented Feb 12, 2011 at 1:47
  • Why? What's wrong with an empty string? Commented Feb 12, 2011 at 1:53
  • @Jonah I try to use array_map('trim', $array).. but this will filter out the NULL variable. Commented Feb 12, 2011 at 20:42
  • @easycoder: you're saying that your program needs to make the distinction between null and empty strings? Commented Feb 13, 2011 at 1:16
  • @easycoder: okay, I edited my answer, take a look. Commented Feb 13, 2011 at 3:57

2 Answers 2

13

Create a proxy function to make sure it's a string before running trim() on it.

function trimIfString($value) { return is_string($value) ? trim($value) : $value; } 

And then of course pass it to array_map() instead.

array_map('trimIfString', $array); 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reminding... the proxy function seems good to me.. i will try that out.. :)
4

Why not just:

$input = !empty($input) ? trim($input) : $input; 

3 Comments

Yes, just realized that. Thanks.
I am used to using isset(), because you normally want to treat null and an empty string as equivalent, as you said in your answer. ;-)
Looks like I had things backwards after changing isset to is_null. Should be fixed now. Let me know if that works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.